Reputation: 544
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.
Upvotes: 0
Views: 602
Reputation: 174696
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
Upvotes: 1