[英]Look for a certain String inside another and count how many times it appears
我试图在文件内容中搜索一个String,我将其放入String中。
我试过使用Pattern
和Matcher
,它适用于这种情况:
Pattern p = Pattern.compile("(</machine>)");
Matcher m = p.matcher(text);
while(m.find()) //if the text "(</machine>)" was found, enter
{
Counter++;
}
return Counter;
然后,我尝试使用相同的代码来查找我有多少标签:
Pattern tagsP = Pattern.compile("(</");
Matcher tagsM = tagsP.matcher(text);
while(tagsM.find()) //if the text "(</" was found, enter
{
CounterTags++;
}
return CounterTags;
在这种情况下,返回值始终为0。
尝试使用下面的代码,顺便说一下不使用Pattern
: -
String actualString = "hello hi how(</machine>) are you doing. Again hi (</machine>) friend (</machine>) hope you are (</machine>)doing good.";
//actualString which you get from file content
String toMatch = Pattern.quote("(</machine>)");// for coverting to regex literal
int count = actualString .split(toMatch, -1).length - 1; // split the actualString to array based on toMatch , so final match count should be -1 than array length.
System.out.println(count);
输出 : - 4
您可以使用Apache commons-lang
util库,完全有一个函数countMatches :
int count = StringUtils.countMatches(text, "substring");
此函数也是null安全的。 我建议你去探索Apache commons库,它们提供了很多有用的常用util方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.