Quantcast
Channel: Reza's Weblog
Viewing all articles
Browse latest Browse all 50

Using Pattern.quote

$
0
0

We know that for replacing all the periods in "a.b.c" we can use replaceAll method of String. It take a regular expression and a replacement string.

This is a mistake: System.out.println("a.b.c".replaceAll(".", "/") ); because "." as a regex means every character; so it replaces all the chars with /.

The following has a compile error because of the need for another back slash:

System.out.println("a.b.c".replaceAll("\.", "/") );

So the correct form would be : System.out.println("a.b.c".replaceAll("\\.", "/") );

From release 5.0 the new static method java.util.regex.Pattern.quote has been introduced. It takes a string as a parameter and adds any necessary escapes, returning a regular expression string that matches the input string exactly.

So we can also write: System.out.println("a.b.c".replaceAll(Pattern.quote("."), "/") );


Viewing all articles
Browse latest Browse all 50

Trending Articles