在字符串中查找句子

时间:2018-05-20 13:38:29

标签: java regex

我有字符串形式的文件内容。我需要在字符串中得到部分句子"My name is scott"的计数,该字符串可以跨越

这样的行
some content ... "My name is scott"  some content ...

some content ... "My name is " +  
    "scott"  some content ...

如果我可以获得两个版本,即第一个,以便在单行中找到给定的输入,那将是很好的。第二个也可以跨行搜索?

1 个答案:

答案 0 :(得分:1)

您可以使用replaceAll替换该中断部分:

" +  
    "
像这样:

String text = "some content ... \"My name is scott\"  some content ...\n"
        + "\n"
        + "some content ... \"My name is \" +  \n"
        + "    \"scott\"  some content ...";
String textToMatche = "My name is scott";
text = text.replaceAll("\"\\s*\\+\\s*\n\\s*\"", "");// Note the regex : \"\s*\+\s*\n\s*\"

结果:

some content ... "My name is scott"  some content ...

some content ... "My name is scott"  some content ...

然后计算出现次数:

Java 9+版

long count = Pattern.compile(Pattern.quote(textToMatche)).matcher(text).results().count();

在Java 9之前

Pattern p = Pattern.compile(Pattern.quote(textToMatche));
Matcher m = p.matcher(text);
int count = 0;
while (m.find()) {
    count += 1;
}

输出

2

ANSICON