Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-based regular expression to allow alphanumeric chars and ', and

Tags:

java

regex

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

like image 990
Mr Albany Caxton Avatar asked Dec 21 '22 12:12

Mr Albany Caxton


2 Answers

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 ([...]).

like image 175
aioobe Avatar answered Dec 24 '22 01:12

aioobe


Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s\\.,]{1," + s.length() + "}$");
like image 34
Herring Avatar answered Dec 24 '22 01:12

Herring