我正在尝试执行简单的正则表达式。基本上我想确定我的字符串中是否有特殊字符,如果是,请检查字符串的每个字符是否有两个特定字符,即hypen和dot。
我似乎在第一位遇到问题,这涉及到我的字符串中是否有特殊字符。
以下是我尝试执行此操作的方法,然后是我遇到问题的字符串:
public static boolean stringValidity(String input) {
int specials = 0;
Pattern p = Pattern.compile("[^a-zA-Z0-9 ]");
Matcher m = p.matcher(input);
boolean b = m.find();
if (b) {
System.out.println("\nstringValidity - There is a special character in my string");
for (int i = 0; i < input.length(); ++i) {
char ch = input.charAt(i);
//if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
++specials;
System.out.println("\nstringValidity - Latest number of special characters is: " + specials);
if((ch == '-') | (ch == '.')) {
specialCharValidity = true;
System.out.println("\nstringValidity - CHAR is valid - specialCharValidity is: " + specialCharValidity + " as char is: " + ch);
} else {
specialCharValidity = false;
System.out.println("\nstringValidity - CHAR is invalid - specialCharValidity is: " + specialCharValidity + " as char is: " + ch);
break;
}
//}
}
} else {
System.out.println("\nstringValidity - There is NO special character in my string");
specialCharValidity = true;
}
return specialCharValidity;
}
下面是我传递给方法的字符串,我希望将其视为具有特殊字符的字符串但测试失败:
"QWERTY"!£$"£$"
"sdfGSDFGSDFG%*^(%*&("
下面是我传递给方法的字符串,我希望不要将其视为具有特殊字符的字符串但测试失败:
"QWE12342134RTY"
"LOREMIPSUM2354214"
任何建议都表示赞赏。
答案 0 :(得分:1)
您可以通过针对以下模式检查字符串来简化代码:
[^a-zA-Z0-9 \-\.]
字符串有效性函数归结为:
public static boolean stringValidity(String input)
{
return Pattern.compile("[^a-zA-Z0-9 \\-\\.]").matcher(input).find() == false;
}
答案 1 :(得分:0)
使用提供的字符串运行代码给出了以下输出:
stringValidity - There is a special character in my string
stringValidity - Latest number of special characters is: 1
stringValidity - CHAR is invalid - specialCharValidity is: false as char is: Q
---
stringValidity - There is a special character in my string
stringValidity - Latest number of special characters is: 1
stringValidity - CHAR is invalid - specialCharValidity is: false as char is: s
---
stringValidity - There is NO special character in my string
---
stringValidity - There is NO special character in my string
---
我想这意味着你用来寻找特殊字符(不是数字或字母)的模式没有任何问题。但我发现您的代码存在以下问题:
specials
的计数,你只需要删除break
行,这样循环就不会在第一个特殊句点中停止; 一些建议
Character.isSpace()
替换为Character.isWhitespace()
,因为第一个版本已弃用; specialCharValidity
以避免潜在问题; Pattern p = Pattern.compile("[^a-zA-Z0-9 ]");
上那样在每次调用时编译相同的模式。编译模式非常耗时,因此您只需在类static public final Pattern p = Pattern.compile("[^a-zA-Z0-9 ]");
上定义一个常量,然后再使用它;