I'm trying to get this regex lines to work but they don't seem to be working (I can't get it print out "matches".
My goal is to read in a string from Scanner and then run this function. If the string has either lower case values OR special characters then I want to call the invalid function and then return NULL. Then in the isValid() method, I'll have it return false and end.
if it contains NUMBERS and UPPERCASE characters only i want to return the string as it is so it can do other things.
I can't seem to get it print out "matches". I'm sure I'm doing this right and it's really frustrating me, I've been checking the forums for different ways but none seem to work.
Thanks for the help.
public static String clean(String str){
String regex = "a-z~@#$%^&*:;<>.,/}{+";
if (str.matches("[" + regex + "]+")){
printInvalidString(str);
System.out.println("matches");
} else{
return str;
}
return null;
}
public static boolean isValid(String validationString){
//clean the string
validationString = clean(validationString);
if (validationString == null){
return false;
}
解决方案
matches will try matching from start of string.If at the start there is not lowercase or Special characters it will fail.Use .find or simply make positive assertion.
^[A-Z0-9]+$
If this passes with matches its a valid string for you.