用空格分隔多个单词的正则表达式?

时间:2021-09-04 20:11:50

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

我需要一个正则表达式来表示2个或更多的空格,例如:

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.

[\w\s]+给我所有的单词,但不确定如何将一个单词排除在验证中。

3 个解决方案

#1


2  

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

不要在字符类中包含空格:\w+\s+\w+ \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\s+\w

#2


1  

word class, space, word class...

词类,空间,词类…

\w+ \w+

\ w + \ w +

#3


0  

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.

这个regex将返回有效的值和无效输入的第一个有效部分。

#1


2  

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

不要在字符类中包含空格:\w+\s+\w+ \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\s+\w

#2


1  

word class, space, word class...

词类,空间,词类…

\w+ \w+

\ w + \ w +

#3


0  

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.

这个regex将返回有效的值和无效输入的第一个有效部分。