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
Use this regular expression pattern ("^[a-zA-Z0-9]*$") .It validates alphanumeric string excluding the special characters
For people (like me) looking for an answer for special characters like Ä etc. just use this pattern:
Only text (or a space): "[A-Za-zÀ-ȕ ]"
Text and numbers: "[A-Za-zÀ-ȕ0-9 ]"
Text, numbers and some special chars: "[A-Za-zÀ-ȕ0-9(),-_., ]"
Regex just starts at the ascii index and checks if a character of the string is in within both indexes [startindex-endindex].
So you can add any range.
Eventually you can play around with a handy tool: https://regexr.com/
Good luck;)
We can achieve this using Pattern and Matcher as follows:
Pattern pattern = Pattern.compile("[^A-Za-z0-9 ]");
Matcher matcher = pattern.matcher(trString);
boolean hasSpecialChars = matcher.find();
Please use this.. it is simplest.
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
StringBuilder builder = new StringBuilder(checkstring);
String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
//change your all special characters to ""
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(builder.toString());
checkstring=matcher.replaceAll("");
To find any number of special characters use the following regex pattern: ([^(A-Za-z0-9 )]{1,})
[^(A-Za-z0-9 )] this means any character except the alphabets, numbers, and space. {1,0} this means one or more characters of the previous block.
(^\W$)
^ - start of the string, \W - match any non-word character [^a-zA-Z0-9_], $ - end of the string