Count All Words
It is another use case for us, In this scenario we don’t provide any Starting and ending boundaries for pattern matching. And also we need change the regex also. Reaming is same as explained in the above and again I take String value but I change regex for this use case I will provide in the below.
Required Regex
"\\b\\w+\\b"
Example
In this example I write java code for count all the words from the given String and display the result.
Java
// Java Program to Count All Words in a String import java.util.regex.Matcher; import java.util.regex.Pattern; public class AllWordCountExample { public static void main(String[] args) { // Input string String inputString = "Welcome to w3wiki Best Online Platform for" + " learning Computer Science Subjects" ; // Regular expression to match words String wordRegex = "\\b\\w+\\b" ; // Create a Pattern object Pattern pattern = Pattern.compile(wordRegex); // Create a Matcher object Matcher matcher = pattern.matcher(inputString); // Count the number of words int wordCount = 0 ; while (matcher.find()) { wordCount++; } // Display the result System.out.println( "Number of words in the string: " + wordCount); } } |
Output
Count a Group of Words in a String Using Regex in Java
Regular Expression is a powerful approach in Java for searching, Manipulating, and matching patterns with specific pattern requirements. In this article, we will learn to count a group of words in a string using regex.
First I explain count a group of words in a string using regex as per requirement, After that I will explain how to count all words in a given String by using regex.
Contact Us