1

我是正则表达式的新手,可以帮助我解决问题

例如我有一个字符串如下,

String str = "this is a hello world string and duplicate starts from here this is a hello world string";

我想使用正则表达式检查以下条件。

if("this is a hello world string" has appeared more than once in String str){
    return false;
}
else{
    return true;
}

如何做到这一点?

4

4 回答 4

1

你可以在没有这样的正则表达式的情况下做到这一点

if(str.indexOf("this is a hello world string") != str.lastIndexOf("this is a hello world string")) { 
    return false;
}
else{
    return true;
}
于 2013-11-13T10:44:32.377 回答
1

您也可以像本例中那样使用正则表达式:

String str1 = "this is a hello world string";
String str2 = "this is a hello world string and duplicate starts from here this is a hello world string";
Pattern pattern = Pattern.compile(str1);
Matcher matcher = pattern.matcher(str2);

int count = 0;

while(matcher.find()){
    count++;
}

if(count > 0) {
     return true;
} else {
     return false;
}

希望能帮助到你。干杯。

于 2013-11-13T10:51:12.990 回答
0

如果您真的想找到两个重复的“事物”而不指定它们是什么,那么您将很难为它编写正则表达式。

这匹配两个“重复的东西”:

(.+)(?=.+)\1

请注意,它找到“任何东西”并断言“其他任何东西”可以在它和它自己的另一个实例之间。

是的,那样并不令人困惑。

于 2013-11-15T08:53:44.927 回答
0

您可以使用以下代码

String duplicatePattern = "(?i)\\b(\\w+)\\b[\\w\\W]*\\b\\1\\b";
    Pattern p = Pattern.compile(duplicatePattern);
    String phrase = "this is a hello world string and duplicate starts from here this is a hello world string";
    Matcher m = p.matcher(phrase);
    String val = null;
    while (m.find()) {
        val = m.group();
        System.out.println("Matching segment is \"" + val + "\"");
        System.out.println("Duplicate word: " + m.group(1)+ "\n");
    }
于 2013-11-13T11:18:00.393 回答