繁体   English   中英

尝试检查字符串是否包含特殊字符或小写Java

[英]Trying to check if string contains special characters or lowercase java

我正在尝试使此正则表达式行起作用,但它们似乎不起作用(我无法将其打印出“匹配项”。

我的目标是从Scanner中读取一个字符串,然后运行此功能。 如果字符串具有小写值或特殊字符,则我想调用无效函数,然后返回NULL。 然后在isValid()方法中,让它返回false并结束。

如果它仅包含NUMBERS和UPPERCASE字符,我想按原样返回该字符串,以便它可以执行其他操作。

我似乎无法将它打印出来“匹配”。 我确定我做对了,这确实让我感到沮丧,我一直在以各种不同的方式检查论坛,但似乎没有一个起作用。

谢谢您的帮助。

  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将尝试从匹配start在string.If的start没有lowercaseSpecial characters就会fail 。使用.find或者干脆做出了积极的断言。

^[A-Z0-9]+$

如果passesmatches的为您有效的字符串。

要匹配数字和大写字符,请使用:

^[\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.

转义的Java字符串版本
of: az~@#$%^&*:;<>.,/}{+
是: "az~@#\\\\$%\\\\^&\\\\*:;<>\\\\.,/}\\\\{\\\\+"

除了检查带有长模式的字符串外,您还可以检查它是否包含大写字母或数字,我可以通过以下方式重写该函数:

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

您的正则表达式将匹配包含无效字符的字符串。 因此,带有有效和无效字符的字符串将与正则表达式不匹配。

验证字符串会更容易:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM