TimeToCodeTheRoad
TimeToCodeTheRoad

Reputation: 7312

Regex: Illegal hexadecimal escape sequence

I am new to Regex..I wrote the following regex to check phone numbers in javascript: ^[0-9\+\-\s\(\)\[\]\x]*$

Now, I try to the same thing in java using the following code:

public class testRegex {

    public static void main(String[] args){

    String regex="^[0-9\\+\\-\\s\\(\\)\\[\\]\\x]*$";

    String phone="98650056";

    System.out.println(phone.matches(regex));

}

However, I always get the following error:

Exception in thread "main" java.util.regex.PatternSyntaxException: 
    Illegal hexadecimal escape sequence near index 21^[0-9\+\-\s\\(\\)\\[\\]\x]*$

Please advise.

Upvotes: 0

Views: 6912

Answers (2)

Bohemian
Bohemian

Reputation: 425083

You have waaaay too many back slashes!

Firstly, to code a literal backslash in java, you must write two of them.

Secondly, most characters lose their special regex meaning when in a character class.

Thirdly, \x introduces a hex literal - you don't want that.

Write your regex like this:

String regex="^[0-9+\\s()\\[\\]x-]*$";

Note how you don't need to escape the hyphen in a character class when it appears first or last.

Upvotes: 0

l'L'l
l'L'l

Reputation: 47179

Since you are trying to match what I assume is x (as in a phone extension), it needs to be escaped with four backslashes, or not escaped at all; otherwise \x is interpreted as a hexidecimal escape code. Because \x is interpreted as a hex code without the two to four additional required chars it's an error.

     [\\x] \x{nn} or {nnnn} (hex code nn to nnnn)
   [\\\\x] x (escaped)
       [x] x

So the pattern becomes:

String regex="^[-0-9+()\\s\\[\\]x]*$";

Escaped Alternatives:

String regex="^[0-9\\+\\-\\s\\(\\)\\[\\]x]*$";
String regex="^[0-9\\+\\-\\s\\(\\)\\[\\]\\\\x]*$";

Upvotes: 4

Related Questions