I want to write a simple regular expression to check if in given string exist any special character. My regex works but I don\'t know why it also includes all numbers, so wh
I have defined one pattern to look for any of the ASCII Special Characters ranging between 032 to 126 except the alpha-numeric. You may use something like the one below:
To find any Special Character:
[ -\/:-@\[-\`{-~]
To find minimum of 1 and maximum of any count:
(?=.*[ -\/:-@\[-\`{-~]{1,})
These patterns have Special Characters ranging between 032 to 047, 058 to 064, 091 to 096, and 123 to 126.
Try using this for the same things - StringUtils.isAlphanumeric(value)
That's because your pattern contains a .-^
which is all characters between and including .
and ^
, which included digits and several other characters as shown below:
If by special characters, you mean punctuation and symbols use:
[\p{P}\p{S}]
which contains all unicode punctuation and symbols.
If you only rely on ASCII characters, you can rely on using the hex ranges on the ASCII table. Here is a regex that will grab all special characters in the range of 33-47
, 58-64
, 91-96
, 123-126
[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]
However you can think of special characters as not normal characters. If we take that approach, you can simply do this
^[A-Za-z0-9\s]+
Hower this will not catch _
^
and probably others.
SInce you don't have white-space and underscore in your character class I think following regex will be better for you:
Pattern regex = Pattern.compile("[^\w\s]");
Which means match everything other than [A-Za-z0-9\s_]
Unicode version:
Pattern regex = Pattern.compile("[^\p{L}\d\s_]");
Here is my regex variant of a special character:
String regExp = "^[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[¿§«»ω⊙¤°℃℉€¥£¢¡®©0-9_+]*$";
(Java code)