Skip to content

Java RegEx – Find Words By Length

Java RegEx – find words by length example shows how to find words by their length (words of a specific or certain length) in a sting using Java regular expression pattern.

How to find words in a Java string by length using a regex pattern?

In order to find words of a specific length, we need to combine two regex expressions. The first one is the word boundary i.e. “\b”. The word boundary “\b”, as the name suggests, matches with any word boundary, for example, at the start or at the end of the string.

Along with that, we also need a pattern repetition expression that is created using curly braces. Please see the below-given table to understand how that works.

We are going to use the first one in our regex pattern as we need to find the word of a certain length. When we combine these two together, our pattern looks like given below.

The whole pattern means a word boundary, followed by any word character 5 times, followed by a word boundary. In this example, we are going to find words of length 5.

Output

You can replace 5 with whatever word length you are looking for. For example, to find a word having the length of 4, the pattern would be “(\\b\\w{4}\\b)”.

The good thing about this pattern is it also works with numbers. See below given example, where I want to find all the numbers having the length of 3 in the string.

Output

If you want to find all the words having a minimum length of 2 and a maximum length of 4, the regex pattern will be “(\\b\\w{2,4}\\b)”.

Output

As you can see from the output, it found words of length 2, 3, and 4. Similarly, if you want to find all the words having a minimum length of 3 and no maximum limit, you can use the below-given code.

Output

As you can see from the output, it found all the words having lengths of more than 3.

If you want to learn more about regular expressions, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.