4

I have a simple regex pattern that verifies names. But When I run it I get illegal character range error. I thought by escaping "\s" it will allow a space but the compiler is still complaining.

public boolean verifyName(String name) {
    String namePattern = "^[\\p{L}]++(?:[',-\\s][\\p{L}]++)*+\\.?$";
    return name.matches(namePattern);
}

and this is the error that i think shouldn't be occurring since a name might contain anny of these [',-\\s]

so where am i not understanding?

1
  • why are you using ++ instead of + Commented Apr 20, 2013 at 7:32

1 Answer 1

12

You can't have a range "from , to whitespace". Perhaps you meant to escape -?

\s is not a space, it's [ \t\r\n\v\f] (space, tab, carriage return, newline, vertical tab or a form feed).

Things that will work:

"[ ',-]"

"[',\\- ]"
Sign up to request clarification or add additional context in comments.

2 Comments

so how should the range be...I want only to allow an apostrophe, hyphen, comma or space
If you want a space, use a space. If you put the hyphen last, you don't need to escape it: [ ',-]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.