简体   繁体   中英

Look for a certain String inside another and count how many times it appears

I am trying to search for a String inside a file content which I got into a String.

I've tried to use Pattern and Matcher , which worked for this case:

Pattern p = Pattern.compile("(</machine>)");
Matcher m = p.matcher(text);
while(m.find()) //if the text "(</machine>)" was found, enter
{
    Counter++;
}

return Counter;

Then, I tried to use the same code to find how many tags I have:

Pattern tagsP = Pattern.compile("(</");
Matcher tagsM = tagsP.matcher(text);
while(tagsM.find()) //if the text "(</" was found, enter
{
    CounterTags++;
}

return CounterTags;

which in this case, the return value was always 0.

Try using the below code , btw not using 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);

Output :- 4

You can use Apache commons-lang util library, there is a function countMatches exactly for you:

int count = StringUtils.countMatches(text, "substring");

Also this function is null-safe. I recommend you to explore Apache commons libraries, they provide a lot of useful common util methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM