An easy way is to check if a string has any non-alphanumeric
characters.
TRY THIS,
StringChecker.java
public class StringChecker {
public static void main(String[] args) {
String str = "abc$def^ghi#jkl";
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
System.out.println(str);
int count = 0;
while (m.find()) {
count = count+1;
System.out.println("position " + m.start() + ": " + str.charAt(m.start()));
}
System.out.println("There are " + count + " special characters");
}
}
And you get the result look like below:
$ java SpecialChars
abc$def^ghi#jkl
position 3: $
position 7: ^
position 11: #
There are 3 special characters
You can pass your own patterns as param in compile methods as per your needs
to checking special characters:
Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");