Trying to check if string contains special characters or lowercase java

和自甴很熟 提交于 2019-12-31 03:01:27

问题


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;
    }

回答1:


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.




回答2:


To match numbers and upper case characters only use:

^[\p{Lu}\p{Nd}]+$

`^`      ... Assert position is at the beginning of the string.
`[`      ... Start of the character class
`\p{Lu}` ... Match an "uppercase letter"
`\p{Nd}` ... Match a "decimal digit"
`]`      ... End of the character class
`+`      ... Match between 1 and unlimited times.
`$`      ... Assert position is at the end of the string.

The escaped java string version
of: a-z~@#$%^&*:;<>.,/}{+
is: "a-z~@#\\$%\\^&\\*:;<>\\.,/}\\{\\+"




回答3:


beside checking the string with long pattern you can check it if contain uppercase or numbers i rewrite the function in this way:

 public static String clean(String str) {

    //String regex = "a-z~@#$%^&*:;<>.,/}{+";
    Pattern regex=Pattern.compile("[^A-Z0-9]");
    if (str.matches(".*" + regex + ".*")) {
        printInvalidString(str);
        System.out.println("matches");
    } else {
        return str;
    }

    return null;
}



回答4:


Your regex will match a string that only has invalid characters. So a string with valid and invalid characters will not match the regex.

Validating the strings would be easier:

if (str.matches([\\dA-Z]+)) return str;
else printInvalidString(str);


来源:https://stackoverflow.com/questions/28873407/trying-to-check-if-string-contains-special-characters-or-lowercase-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!