18

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?

String s = """;    // ?
informatik01
  • 16,038
  • 10
  • 74
  • 104
Gigalala
  • 439
  • 1
  • 8
  • 24
  • 2
    possible duplicate of [How to enter quotes in a String?](http://stackoverflow.com/questions/3559063/how-to-enter-quotes-in-a-string) or [Java, escaping (using) quotes in a regex](http://stackoverflow.com/questions/6398365/java-escaping-using-quotes-in-a-regex) or ... – Brian Roach May 26 '13 at 17:06

2 Answers2

36

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:

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

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 3
    A fun one to match content inside quotes which I often use for properties in xml tags is `"[^"]*"` (or, as escaped java string, `"\"[^\"]*\""`). Impossible to bleed out ;) – Nyerguds May 31 '16 at 13:03
10

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

stinepike
  • 54,068
  • 14
  • 92
  • 112