Skip to main content

APIzation: Replication Package

[Q#16761596][A#16764615] How to represent the double quotes character (") in regex?

https://stackoverflow.com/q/16761596

I need to use regex, to check if a string starts with a double quotes character (") and ends with a double quotes character too. The problem is I can't use a double quotes character, cause it gets confused. Is there any other way to represent a double quotes character " in regex, or in string in general?

Answer

https://stackoverflow.com/a/16764615

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them. This code will test if your String matches: Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

APIzation

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}
package com.stackoverflow.api;

public class Human16764615 {

  public static boolean matchDoubleQuotesRegex(String str) {
    return str.matches("\".*\"");
  }
}

package com.stackoverflow.api;

/**
 * How to represent the double quotes character (") in regex?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/16764615">https://stackoverflow.com/a/16764615</a>
 */
public class APIzator16764615 {

  public static void representCharacter(String str) throws Exception {
    if (str.matches("\".*\"")) {
      // this string starts and end with a double quote
    }
  }
}