正则表达式检查字符串是否只包含字母字符

时间:2018-02-18 15:57:48

标签: java regex

下面的代码块需要检查输入字符串是否只包含字母字符,如果是,则不需要采取进一步的操作。如果它包含数字或特殊字符,那么代码的第二部分需要执行。

目前代码没有按预期工作。它正确检查字符串WIBBLETAX,但也不对字符串($40,x)执行第二次检查。由于($40,x)包含特殊字符,我希望它采取进一步操作并执行else语句。

我需要在此更改哪些内容才能获得我瞄准的功能?

private void checkNumericValues(String token)
    {
        token = token.toUpperCase();

        Pattern p = Pattern.compile("[A-Z]"); //check to see if token is only alphabetical characters, if so token is a branch label and does not need checked
        Matcher m = p.matcher(token);

        if(m.find())
        {
            System.out.println("Token " + token + " is a branch label and does not require value checking");
        }
        else //check numerical value of token to ensure it is not above 0xFF
        {
            String tokenNumerics = token.replaceAll("[^0-9ABCDEFabcdef]", ""); //remove all non-numerical characters from string
            System.out.println("TN: " + tokenNumerics);
            int tokenDecimal = Utils.HexToDec(tokenNumerics); //convert hex value to decimal  
            System.out.println("TokenDecimal: " + tokenDecimal);

            if(tokenDecimal > 255) //if numerical value is greater than 0xFF
            {
                errorFound = true;
                setErrorMessage(token + " contains value that is greater than 0xFF (255)");
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,那么解决方案就是

Pattern p = Pattern.compile("^[A-Z]+$");

说明:这将匹配完全由字母组成的字符串,并且它们至少包含一个字母。

编辑:如上所述,字符串始终为大写。

附加说明:我会小心使用else语句中的代码。我没有尝试过您的代码,但我很确定如果您有一个类似(10,APPLE)的字符串,那么您将获得大于10A十六进制基数的FF。 如果您需要该部分的帮助,请指定您输入的格式。