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

时间:2014-10-11 08:16:42

标签: java regex string

假设我有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中得到真实,因为它具有' SUM'在里面。但是,因为它也有' SUMMER'它给了我假的。

我可以使用任何图书馆吗?要么 有没有其他方法可以得到我的预期结果?

谢谢,
大地。

4 个答案:

答案 0 :(得分:1)

由于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必须以行锚^的空格或开头开头。
  • SUM(?=\\s|$)断言字符串SUM必须后跟行锚$的空格或末尾。

答案 1 :(得分:0)

这是我试过的

    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

答案 2 :(得分:0)

您的预期结果只是检查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());
}

但坦率地说,你的代码工作正常,因为&#39;我搜索的字符串有&#34; SUM&#34;而不是&#34; SUMMER&#34;&#39; 。想一想。

答案 3 :(得分:0)

^.*?\bSUM\b.*$

使用此功能。\b会确保它与SUM匹配,而不是SUMMER

参见演示。

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