[英]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.