Java正则表达式字符串匹配(喜欢和不喜欢)



假设我有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);
    }
}

现在,我需要得到字符串3的true,其中有"SUM"。但是,由于它也有"SUMMER",它给了我false。

有什么图书馆我可以用吗?或有其他方法可以得到我的预期结果吗?

谢谢,
普里特维。

由于matches试图将模式与整个字符串匹配(检查整个字符串是否与给定模式匹配),因此需要在模式的第一个和最后一个添加.*。字边界b将完成此工作,但它也匹配输入FOO:SUM:BAR 中的字符串SUM

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前面必须有一个空格或线路锚^的开头
  • SUM(?=\s|$)断言字符串SUM后面必须跟有空格或线锚$的末尾

以下是我尝试的内容

    String patt = ".*?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

您的预期结果只是检查String是否包含SUM单词(用户Victor Sorokin已经建议)。为此,你可以简单地使用单词边界。我只是稍微简化了你的代码。

String[] strings = {"THE SUM OF TWO","HOT SUMMER","SUM IN SUMMER"};
Pattern pat = Pattern.compile(".*\bSUM\b.*");
for(String string : strings){
    System.out.println(pat.matcher(string).matches());
}

但坦率地说,您的代码可以很好地满足"我搜索具有"SUM"而不是"SUMMER"的字符串"的要求。想一想。

^.*?bSUMb.*$

使用这个。b将确保它匹配SUM而不是SUMMER

请参阅演示。

http://regex101.com/r/vR4fY4/5

最新更新