java - Regex: Illegal hexadecimal escape sequence -


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

now, try same thing in java using 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, following error:

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

please advise.

since trying match assume x (as in phone extension), needs escaped 4 backslashes, or not escaped @ all; otherwise \x interpreted hexidecimal escape code. because \x interpreted hex code without 2 4 additional required chars it's error.

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

so pattern becomes:

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

escaped alternatives:

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

Comments

Popular posts from this blog

Need help in packaging app using TideSDK on Windows -

c++ - boost interprocess mutex in managed_shared_memory -