Java-based regular expression to allow alphanumeric chars and ', and
I'm new to regular expressions in Java and I need to validate if a string has alphanumeric chars, commas, apostrophes and full stops (periods) only. Anything else should equate to false.
Can anyone give any pointers?
I have this at the moment which I believe does a开发者_如何学JAVAlphanumerics for each char in the string:
Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s]{1," + s.length() + "}");
Thanks
Mr Albany Caxton
I'm new to regular expressions in Java and I need to validate if a string has alphanumeric chars, commas, apostrophes and full stops (periods) only.
I suggest you use the \p{Alnum}
class to match alpha-numeric characters:
Pattern p = Pattern.compile("[\\p{Alnum},.']*");
(I noticed that you included \s
in your current pattern. If you want to allow white-space too, just add \s
in the character class.)
From documentation of Pattern
:
[...]
\p{Alnum}
An alphanumeric character:[\p{Alpha}\p{Digit}]
[...]
You don't need to include ^
and {1, ...}
. Just use methods like Matcher.matches
or String.matches
to match the full pattern.
Also, note that you don't need to escape .
within a character class ([
...]
).
Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s\\.,]{1," + s.length() + "}$");
Keep it simple:
String x = "some string";
boolean matches = x.matches("^[\\w.,']*$");
精彩评论