Reputation: 43
I'm new to regular expressions...
I have a problem about the regular expression that will match a string only contains:
0-9, a-z, A-Z, space, comma, and single quote?
If the string contain any char that doesn't belong the above expression, it is invalid.
Is that something like:
Pattern p = Pattern.compile("\\s[a-zA-Z0-9,']");
Matcher m = p.matcher("to be or not");
boolean b = m.lookingAt();
Thank you!
Upvotes: 0
Views: 3655
Reputation: 690
Note that \s will match any whitespace character (including newlines, tabs, carriage returns, etc.) and not only the space character.
You probably want something like this:
"^[a-zA-Z0-9,' ]+$"
Upvotes: 1
Reputation: 336158
You need to include the space inside the character class and allow more than one character:
Pattern p = Pattern.compile("[\\sa-zA-Z0-9,']*");
Matcher m = p.matcher("to be or not");
boolean b = m.matches();
Upvotes: 2
Reputation: 115338
Fix your expression adding bounds:
Pattern p = Pattern.compile("^\\s[a-zA-Z0-9,']+$");
Now your can say m.find()
and be sure that this returns true
only if your string contains the enumerated symbols only.
BTW is it mistake that you put \\s
in the beginning? This means that the string must start from single white space. If this is not the requirement just remove this.
Upvotes: 2