我有字符串形式的文件内容。我需要在字符串中得到部分句子"My name is scott"
的计数,该字符串可以跨越
some content ... "My name is scott" some content ...
some content ... "My name is " +
"scott" some content ...
如果我可以获得两个版本,即第一个,以便在单行中找到给定的输入,那将是很好的。第二个也可以跨行搜索?
答案 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 ...
然后计算出现次数:
long count = Pattern.compile(Pattern.quote(textToMatche)).matcher(text).results().count();
Pattern p = Pattern.compile(Pattern.quote(textToMatche));
Matcher m = p.matcher(text);
int count = 0;
while (m.find()) {
count += 1;
}
输出
2