Java Regex to limit the number of words in input

In this java regex tutorial, we will learn to test whether number of words in input text is between some minimum and maximum limit.

The following regex is very similar to the previous tutorial of limiting the number of nonwhitespace characters, except that each repetition matches an entire word rather than a single nonwhitespace character. It matches between 2 and 10 words, skipping past any non-word characters, including punctuation and whitespace:

Regex : ^\\W*(?:\\w+\\b\\W*){2,10}$

List<String> inputs = new ArrayList<String>();
      
inputs.add("LOKESH");  //Incorrect
inputs.add("JAVA CRAZY");  
inputs.add("LOKESH GUPTA INDIA");  
inputs.add("test whether number of words in input text is between some minimum and maximum limit");  //Incorrect

String regex = "^\\W*(?:\\w+\\b\\W*){2,10}$";

Pattern pattern = Pattern.compile(regex);

for (String input : inputs)
{
    Matcher matcher = pattern.matcher(input);
    System.out.println(matcher.matches());
}

Output:

false
true
true
false

I will advise to play with above simple regular expression to try more variation.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.