String regex = "\\[dog\\]" ; String target = "[dog]"; if ( target.matches( regex ) ) System.out.println("Not so easy, is it?");
The String
literal for a regular expression
needs two backslashes where the resulting RE has only one.
However, sometimes you need a single backslash
in the String
literal
to escape a quote mark you want
inside the RE.
In this case, you don't want the backslash to remain in
the RE.
The best way to sort through this mess is to first write down the RE you want, complete with quote marks and backslashes. Once that is done, write the string literal by inserting single backslashes where needed to escape the quote marks and backslashes in the RE. With a bit of practice you too can be an escape artist.
Desired Regular Expression without " delimiters | Java String | Matches |
---|---|---|
\[dog\] | String RE = "\\[dog\\]"; | [dog] |
\\cat | String RE = "\\\\cat"; | \cat |
3\.14159 | String RE = "3\\.14159" | 3.14159 |
A\+ | String RE = "A\\+" | A+ |
"Quoth He" | String RE = "\"Quoth He\"" | "Quoth He" |
"Quoth He"|"Quoth She" | String RE = "\"Quoth He\"|\"Quoth She\"" | "Quoth She" |
Write the String
literal you would need to specify the
regular expression \+?[0-9]+\.[0-9]*