I'm attempting a simple regex execution. Essentially I want to determine if I've got special characters in my string and if so check each character of the string for two specific characters i.e. hypen and dot.
I seem to be having a problem in the first bit which involves determining if I've got special characters in my string.
Below is my method which I attempt to do this followed by the strings I'm having issues 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 are strings I passed to the method which I expected to be considered as strings with special characters but the test failed:
"QWERTY"!£$"£$"
"sdfGSDFGSDFG%*^(%*&("
Below are strings I passed to the method which I expected NOT to be considered as strings with special characters but the test failed:
"QWE12342134RTY"
"LOREMIPSUM2354214"
Any suggestions are appreciated.
You can simplify your code by checking the string against the following pattern:
[^a-zA-Z0-9 \-\.]
The string validity function boils down to:
public static boolean stringValidity(String input)
{
return Pattern.compile("[^a-zA-Z0-9 \\-\\.]").matcher(input).find() == false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With