团队,我有一个任务。即,我想检查98%数据的 blcvk。我试图写一些正则表达式,但它给出了连续的错误。
String str="OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
if(str.matches("[0-9][0-9]%"))
但它返回错误。
响应非常感谢。
使用模式/匹配器/查找方法。matches将正则表达式应用于整个字符串。
Pattern pattern = Pattern.compile("[0-9]{2}%");
String test = "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(test);
if(matcher.find()) {
System.out.println("Matched!");
}
尝试:
str.matches(".*[0-9][0-9]%.*")
或(\d=数字):
str.matches(".*\\d\\d%.*")
匹配模式也应该匹配之前/之后的字符,98%这就是为什么你应该添加.*
评论:
您可以像其他人建议的那样使用模式匹配器,如果您想98%从字符串中提取它特别有效 - 但如果您只是想查找是否有匹配 - 我发现.matches()使用起来更简单。
你可以试试这个正则表达式\d{1,2}(\.\d{0,2})?%,这将匹配98%或百分比与十进制值一样98.56%。
Pattern pattern = Pattern.compile("\\d{1,2}(\\.\\d{0,2})?%");
String yourString= "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()) {
System.out.println(matcher.group());
}
str.matches("[0-9][0-9]%")实际上应用了这个正则表达式^[0-9][0-9]%$,它锚定在开始和结束处。其他人已经描述了解决方案。