I am trying to execute a simple regular expression. Essentially, I want to determine if I have special characters in my string, and if so, check each character of the string for two specific characters, for example, hypen and dot.
It seems that I have a problem in the first bit, which includes determining if I have special characters in my string.
Below is my method that I am trying to do, followed by the lines that I'm having problems with:
public static boolean stringValidity(String input) { int specials = 0; Pattern p = Pattern.compile("[^a-zA-Z0-9 ]"); Matcher m = p.matcher(input); boolean b = m.find(); if (b) { System.out.println("\nstringValidity - There is a special character in my string"); for (int i = 0; i < input.length(); ++i) { char ch = input.charAt(i); //if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) { ++specials; System.out.println("\nstringValidity - Latest number of special characters is: " + specials); if((ch == '-') | (ch == '.')) { specialCharValidity = true; System.out.println("\nstringValidity - CHAR is valid - specialCharValidity is: " + specialCharValidity + " as char is: " + ch); } else { specialCharValidity = false; System.out.println("\nstringValidity - CHAR is invalid - specialCharValidity is: " + specialCharValidity + " as char is: " + ch); break; } //} } } else { System.out.println("\nstringValidity - There is NO special character in my string"); specialCharValidity = true; } return specialCharValidity; }
Below is the line that I passed to the method, which, as I expected, was considered a line with special characters, but the test failed:
"QWERTY"!Β£$"Β£$" "sdfGSDFGSDFG%*^(%*&("
Below the lines that I passed to the method I was expecting should NOT be considered as strings with special characters, but the test failed:
"QWE12342134RTY" "LOREMIPSUM2354214"
Any suggestions are welcome.
source share