xingbin
xingbin

Reputation: 28279

Redundant Character Escape of .(dot) in java regex

As far as I know, . is a metacharacter in java regex. But when I use it as below:

    String s = "1.2.3.4";
    Pattern pattern = Pattern.compile("[\\.]");

I got a Redundant Character Escape warning from IntelliJ IDEA. Any explaination?

Upvotes: 3

Views: 1946

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

It is because of the square brackets. Check this:

Pattern pattern = Pattern.compile("[\\.]");
System.out.println(pattern.matcher("").find());
System.out.println(pattern.matcher(".").find());
System.out.println(pattern.matcher("a").find());

false

true

false

pattern = Pattern.compile("[.]");
System.out.println(pattern.matcher("").find());
System.out.println(pattern.matcher(".").find());
System.out.println(pattern.matcher("a").find());

false

true

false

If you were to use the dot outside of the square brackets your escape would be required to capture a dot rather than any character.

Upvotes: 6

Related Questions