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

Regex \\b\\w+\\b matches words. - Matcher finds each word occurrence. - Counter increments for each match. - Together demonstrates regex word counting. Conclusion: Shows how to count words in string using regex.

Quick Links to Explore