Stewie Griffin
Stewie Griffin

Reputation: 9337

Regex for more than one word separated by space?

I need a regex for 2 or more words separated by space, eg:

Test            //invalid
Test two        //valid
Test two three  //valid
Test-two        //invalid

[\w\s]+ gives me all the words, but not sure how to exclude 1 word from validation.

Upvotes: 3

Views: 7886

Answers (3)

Gonzalo
Gonzalo

Reputation: 184

I know its late but for future views

/(\w+\s+[^-])+\S[^-]+/

This regex will return valid ones and the first valid part of the invalid inputs.

Upvotes: 1

SierraOscar
SierraOscar

Reputation: 17647

word class, space, word class...

\w+ \w+

Upvotes: 1

Mr. Llama
Mr. Llama

Reputation: 20919

Don't include the spaces in the character class: \w+\s+\w+

By leaving the spaces in the character class, you've specified that you want any number of word character or spaces, which will quickly gobble up the whole string. By separating the word and space classes, you specify that you want "any number of word characters followed by any number of space characters, then some more word characters".

Unless you're looking to capture the words, remove the quantifier from them as you don't care how long the words are, merely that they are present: \w\s+\w

Upvotes: 3

Related Questions