简体   繁体   中英

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.

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

词类,空间,词类......

\\w+ \\w+

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM