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 alphanumerics for each char in the string:
Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s]{1," + s.length() + "}");
Thanks
Mr Albany Caxton
I suggest you use the
\p{Alnum}class to match alpha-numeric characters:(I noticed that you included
\sin your current pattern. If you want to allow white-space too, just add\sin the character class.)From documentation of
Pattern:You don’t need to include
^and{1, ...}. Just use methods likeMatcher.matchesorString.matchesto match the full pattern.Also, note that you don’t need to escape
.within a character class ([…]).