Skip to content
Advertisement

Regex to match words of a certain length

I would like to know the regex to match words such that the words have a maximum length. for eg, if a word is of maximum 10 characters in length, I would like the regex to match, but if the length exceeds 10, then the regex should not match.

I tried

^(w{10})$

but that brings me matches only if the minimum length of the word is 10 characters. If the word is more than 10 characters, it still matches, but matches only first 10 characters.

Advertisement

Answer

I think you want bw{1,10}b. The b matches a word boundary.

Of course, you could also replace the b and do ^w{1,10}$. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.

Since it’s Java, you’ll actually have to escape the backslashes: "\b\w{1,10}\b". You probably knew this already, but it’s gotten me before.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement