- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to count a group of words in a string using Java
Problem Description
How to count a group of words in a string?
Solution
Following 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
Advertisements