简体   繁体   中英

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) . Since ($40,x) contains special characters I want it to take further action and execute the else statement.

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. 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. If you want help for that part please specify the format of your input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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