0

I have a small query regarding representing the space in java regular Expression.

I want to restrict the name and for that i have defined an pattern as

Pattern DISPLAY_NAME_PATTERN = compile("^[a-zA-Z0-9_\\.!~*()=+$,-\s]{3,20}$");

but eclipse indicating it as error "Invalid escape sequence".It is saying it for "\s" which according to

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

is a valid predefined class.

What am i missing.Could anyone help me withit.

Thanks in advance.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Learner
  • 544
  • 1
  • 8
  • 19
  • then i am getting Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.util.regex.PatternSyntaxException: Illegal character range near index 25 ^[a-zA-Z0-9_\.!~*()=+$,-\s]{3,20}$ – Learner Dec 09 '14 at 05:32
  • possible duplicate of [Java doesn't work with regex \s, says: invalid escape sequence](http://stackoverflow.com/questions/2733255/java-doesnt-work-with-regex-s-says-invalid-escape-sequence) – Joel Brewer Dec 09 '14 at 05:50
  • @JoelBrewer no, escaping only won't solve his problem. – Avinash Raj Dec 09 '14 at 05:54
  • @AvinashRaj ahh. I see :) – Joel Brewer Dec 09 '14 at 05:55

1 Answers1

1

You need to escape the \ in \s one more time. And also, you don't need to escape the . inside a character class. . and \\. inside a character class matches a literal dot.

Pattern DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_.!~*()=+$,\\s-]{3,20}$");

And also put the - at the first or at the last inside the character class. Because - at the center of character class may act as a range operator. regex.PatternSyntaxException: Illegal character range exception is mainly because of this issue, that there isn't a range exists between the , and \\s

If you want to do a backslash match, then you need to escape it exactly three times.

Pattern DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_.\\\\!~*()=+$,\\s-]{3,20}$");

Example:

System.out.println("foo-bar bar8998~*foo".matches("[a-zA-Z0-9_.\\\\!~*()=+$,\\s-]{3,20}"));   // true
System.out.println("fo".matches("[a-zA-Z0-9_.\\\\!~*()=+$,\\s-]{3,20}"));  // false
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Now this is strange when i move "^[a-zA-Z0-9_.!~*()=+$,-\\s]{3,20}$" in last then i am getting exception but if i move it in middle then it is working fine.do you have any idea – Learner Dec 09 '14 at 05:38
  • What's the exception you got? You need to move `-` inside the charcater class from the middle to the last inside the same character class itself. – Avinash Raj Dec 09 '14 at 05:42