Reputation: 346
Im currently using the following regex to check that the input is 2 or 3 words only. The words should not contain any numerical values.
^\s*([a-zA-Z]+\s*){2,3}$
This however allows the input "Tommy" (1 word) to be allowed when it should not be.
Thank you
Upvotes: 1
Views: 2210
Reputation: 785126
You can use this regex to match 2 or 3 words separated by a horizontal space:
^\h*[a-zA-Z]+\h+[a-zA-Z]+(?:\h+[a-zA-Z]+)?$
You can also use split
function and check the length:
String[] words = input.split("\\h+"):
if (words.length == 2 || words.length == 3) {
// 2 or 3 words found
}
Upvotes: 2
Reputation: 43169
You could implement word boundaries as in
^\s*(?:(?:\b[a-zA-Z]+\b)\s*){2,3}$
# -^- -^-
Upvotes: 2