![]() |
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. Count a group of wordsFor this use case first I take one String variable with a value I take below the String value you can take another String value you want. After that we need to count a group of words means the group can contain certain boundaries like the starting position of a group of words and the ending position of a group of words. To count words in the group, we need to create a regex pattern for this logic. Required Pattern"\\b" + startingBoundary + "\\b\\s*(.*?)\\s*\\b" + endingBoundary + "\\b" Explanation of Pattern:
Java Program to Count group of wordsJava
OutputOutput while No match found between boundariesExplaination of the above Program:In this above code first I import the required packages with required classes those Pattern and Matcher. After That I take One Sting value. After that I choose starting and ending boundary values from given string and assign them to two variables namely startingBoundary and endingBoundary. Now I will apply the regex pattern as per out requirement. After apply the regex we get some result. This result is stored in String type array. After that I used Pattern and Matcher classes for Matching the required pattern using Matcher class, then I count the size of that words using that array. Finally I print the result using print statement. If no words are found between given boundaries then we got message like No match found between boundaries. I will provide output images in the below for better understanding the concept with java code. Count All WordsIt 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" ExampleIn this example I write java code for count all the words from the given String and display the result. Java
Output |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |