go to previous page   go to home page   go to next page
String test = "\"This is a backslash \\\", she said.";
System.out.print( test );

Answer:

"This is a backslash \", she said.


Escaping Metacharacters in a Regular Expression

Regular ExpressionMatches
\[dog\] [dog]
\\cat \cat
3\.141593.14159
A\+A+

Recall (from Chapter 7) that you need a backslash in a regular expression to remove the meaning of a metacharacter.

When using the matches(String RE) method, the argument RE must refer to a Java String. So sometimes you need a String that contains backslashes that are part of the RE. To do this, use two backslashes in the String literal for each backslash you want in the regular expression.

So, if the RE you want to end up with is:

3\.14159

Then the String literal should be:

"3\\.14159"

QUESTION 11:

Say that you want the regular expression \[dog\] which literaly matches the seven characers: \[dog\]

Write the code that puts those characters into a String:

String regex =  ;

String target = "[dog]";

if ( target.matches( regex ) )
  System.out.println("Not so easy, is it?");