This question already has an answer here:
-
How to enter quotes in a Java string?
9 answers
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 = """; // ?
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.
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.");