简体   繁体   English

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

[英]Regex to check if string only contains alphabetical characters

The code block below needs to check whether an input string contains only alphabetical characters, if it does then no further action needs to be taken. 下面的代码块需要检查输入字符串是否仅包含字母字符,如果确实包含,则无需采取进一步的措施。 If it contains numerical or special characters then the second part of the code needs to be executed. 如果它包含数字或特殊字符,则需要执行代码的第二部分。

At the moment the code doesn't work as intended. 目前,代码无法正常工作。 It correctly checks the string WIBBLE or TAX but also doesnt perform the second check on the string ($40,x) . 它正确检查字符串WIBBLETAXWIBBLE字符串($40,x)进行第二次检查。 Since ($40,x) contains special characters I want it to take further action and execute the else statement. 由于($40,x)包含特殊字符,因此我希望它采取进一步的措施并执行else语句。

What do I need to change here to get the functionality I'm aiming for? 为了获得我想要的功能,我需要在此处进行哪些更改?

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

If I understood well your problem, then the solution is 如果我了解您的问题,那么解决方案是

Pattern p = Pattern.compile("^[AZ]+$"); .

Explanation: this will match strings that are entirely made by alphabetical letters and such that they contain at least one letter. 说明:这将匹配完全由字母组成的字符串,并且它们至少包含一个字母。

Edit: as one noted, the string is always uppercase. 编辑:如前所述,字符串始终为大写。

Additional notes: I would be careful with the code in the else statement. 附加说明:我会谨慎处理else语句中的代码。 I have not tried your code but I am pretty sure that if you have a string like (10,APPLE) , then you will obtain 10A which is bigger than FF in hex base. 我还没有尝试过您的代码,但是我很确定,如果您有一个类似(10,APPLE)的字符串,那么您将获得10A ,以十六进制为基础大于FF If you want help for that part please specify the format of your input. 如果您需要有关该部分的帮助,请指定输入格式。

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

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