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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.