How to count a group of words in a string?
SolutionFollowing example demonstrates how to count a group of words in a string with the help of matcher.groupCount() method of regex.Matcher class.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherGroupCountExample { public static void main(String args[]) { Pattern p = Pattern.compile("J(ava)"); String candidateString = "This is Java. This is a Java example."; Matcher matcher = p.matcher(candidateString); int numberOfGroups = matcher.groupCount(); System.out.println("numberOfGroups =" + numberOfGroups); } }Result
The above code sample will produce the following result.
numberOfGroups = 3
The following is an example to to count a group of words in a string.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String s1 = "SairamkrishnaxxxxxMammahe"; Pattern pattern = Pattern.compile("Sairamkrishna"); Matcher matcher = pattern.matcher(s1); int count = 0; while (matcher.find())count++; System.out.println(count); } }
The above code sample will produce the following result.
1
java_regular_exp.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4