Java regex that allows alphanumeric characters and ', and

I'm new to regular expressions in Java, and I need to check if a string has only alphanumeric characters, commas, apostrophes, and full stops (periods). Everything else should be false.

Can anyone point to pointers?

I have this at that moment, which I believe contains the alphanumeric characters for each char in the string:

Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s]{1," + s.length() + "}"); 

thanks

Mr. Albany Caxton

+4
source share
3 answers

I'm new to regular expressions in Java, and I need to check if the string has alphanumeric characters , commas , apostrophes, and full stops (periods only).

I suggest you use the \p{Alnum} class to match alphanumeric characters:

 Pattern p = Pattern.compile("[\\p{Alnum},.']*"); 

(I noticed that you included \s in your current pattern. If you want to allow white space, just add \s to the character class.)

From the Pattern documentation :

[...]

\p{Alnum} Alphanumeric character: [\p{Alpha}\p{Digit}]

[...]


You do not need to include ^ and {1, ...} . Just use methods like Matcher.matches or String.matches to match the full pattern.

Also note that you do not need to exit . inside a character class ( [ ... ] ).

+10
source
 Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s\\.,]{1," + s.length() + "}$"); 
+1
source

Keep it simple:

 String x = "some string"; boolean matches = x.matches("^[\\w.,']*$"); 
0
source

All Articles