Look for a specific line inside another and count how many times it appears

I am trying to find a line inside the contents of a file that I received in a line.

I tried using Pattern and Matcher that 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 out 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; 

in this case, the return value is always 0.

+5
source share
2 answers

Try using the code below without btw 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

+5
source

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

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

Also this function is null. I recommend that you study the Apache commons libraries, they provide many useful common usage methods.

+3
source

All Articles