假设我有 3 个字符串
String string1 = "THE SUM OF TWO"
String string2 = "HOT SUMMER"
String string3 = "SUM IN SUMMER"
现在,我搜索包含“SUM”而不是“SUMMER”的字符串。
String patt = ".*?SUM.*?"
String notpatt = ".*?SUMMER.*?"
Pattern regex = Pattern.complie(patt)
Pattern nonregex = Pattern.complie(notpatt)
循环遍历这里的每个字符串
if(regex.matcher(string1).matches()){
if(nonregex.matcher(string1).matches()){
System.out.println(false);
}
else{
System.out.println(true);
}
}
现在,我需要为 string3 获取 true,其中包含“SUM”。但是,因为它也有“SUMMER”,所以它给了我错误的信息。
有我可以使用的库吗?或者 还有其他方法可以达到我的预期结果吗?
谢谢,
普里特维。
最佳答案
自 matches
尝试将模式与整个字符串进行匹配(检查整个字符串是否与给定模式匹配),您需要添加 .*
在你的模式中的第一个和最后一个。字边界\b
将完成这项工作,但它也匹配字符串 SUM
在输入 FOO:SUM:BAR
String patt = ".*?(?<=\\s|^)SUM(?=\\s|$).*";
Pattern regex = Pattern.compile(patt);
String[] test = {"THE SUM OF TWO", "HOT SUMMER", "SUM IN SUMMER"};
for (String s: test) {
if(regex.matcher(s).matches()){
System.out.println(true);
} else {
System.out.println(false);
}
输出:
true
false
true
说明:
-
(?<=\\s|^)
断言字符串SUM
前面必须有空格或行 anchor^
的开头. -
SUM(?=\\s|$)
断言字符串SUM
后面必须跟一个空格或行尾 anchor$
.
关于Java正则表达式字符串匹配(like和not like),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26312576/