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'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() + "}$");
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With