benjo456
benjo456

Reputation: 346

Regex to match either 2 or 3 words, but not 1 word

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

Answers (2)

anubhava
anubhava

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]+)?$

RegEx Demo

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

Jan
Jan

Reputation: 43169

You could implement word boundaries as in

^\s*(?:(?:\b[a-zA-Z]+\b)\s*){2,3}$
#         -^-        -^- 

See a demo on regex101.com.

Upvotes: 2

Related Questions