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.
Solution 1:
I think you want \b\w{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.
Solution 2:
^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$ # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.