[英]Regex to check if string only contains alphabetical characters
下面的代码块需要检查输入字符串是否仅包含字母字符,如果确实包含,则无需采取进一步的措施。 如果它包含数字或特殊字符,则需要执行代码的第二部分。
目前,代码无法正常工作。 它正确检查字符串WIBBLE
或TAX
但WIBBLE
字符串($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)");
}
}
}
如果我了解您的问题,那么解决方案是
Pattern p = Pattern.compile("^[AZ]+$");
。
说明:这将匹配完全由字母组成的字符串,并且它们至少包含一个字母。
编辑:如前所述,字符串始终为大写。
附加说明:我会谨慎处理else语句中的代码。 我还没有尝试过您的代码,但是我很确定,如果您有一个类似(10,APPLE)
的字符串,那么您将获得10A
,以十六进制为基础大于FF
。 如果您需要有关该部分的帮助,请指定输入格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.