Count Words Using Regex

This program counts words in a string using regex.

Problem Statement

Write a Java program to count words in a given string using regex.

Source Code

1 import java.util.regex.*;
2 public class RegexWordCount {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Regex Word Count");
5 String str="Eduinq is creating string programs";
6 Pattern p=Pattern.compile("\\b\\w+\\b");
7 Matcher m=p.matcher(str);
8 int count=0;
9 while(m.find()) count++;
10 System.out.println("Word count: "+count);
11 }
12 }

Program Output

Eduinq Regex Word Count
Word count: 5

Explanation

The regex \b\w+\b matches complete words using word boundaries, and the Matcher's find() method is called in a loop to count each match, demonstrating regex-based word counting.

Quick Links to Explore