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.
The count() method can count the number of occurrences of a substring within a larger string. The Python string method count() searches through a string. It returns a value equal to the number of times a substring appears in the string.
count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
Using the indexOf() method The indexOf() method in java is a specialized function to find the index of the first occurrence of a substring in a string.
Given a string and a character, the task is to make a function which count occurrence of the given character in the string. Examples: Input : str = "geeksforgeeks" c = 'e' Output : 4 'e' appears four times in str. Input : str = "abccdefgaa" c = 'a' Output : 3 'a' appears three times in str.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With