如何匹配“两个或多个单词” [英] How to match "two or more words"
问题描述
在给定的字符串中,我试图验证至少有两个单词,其中单词被定义为任何非数字字符,例如
In a given string, I'm trying to verify that there are at least two words, where a word is defined as any non-numeric characters so for example
// Should pass
Phil D'Sousa
Billy - the - Kid
// Should Fail
Joe
454545 354434
我认为这应该有效:
(\b\D*?\b){2,}
但它没有。
推荐答案
您可以全局搜索单词并检查 .match的长度( )
如果找到匹配项:
You can globally search for a "word" and check the length of the .match()
if a match is found:.
如果找到两个或两个以上的单词,那就很好了:
If two or more words are found, you're good:
var matches = string.match(/\b[^\d\s]+\b/g);
if ( matches && matches.length >= 2 )
{ /* Two or more words ... */ };
您可以将单词定义为 \ b [^ d \ ] + \ b
,这是一个单词边界 \b
,一个或多个非数字和非空格 [ ^ d \s] +
,以及另一个单词边界 \b
。您必须确保为 g rel =nofollow noreferrer>正则表达式 找到所有可能的匹配。
You can define a word as \b[^d\s]+\b
, which is a word boundary \b
, one or more non digits and non whitespaces [^d\s]+
, and another word boundary \b
. You have to make sure to use the global option g
for the regex to find all the possible matches.
您可以调整正则表达式中单词的定义。诀窍是使用 .match()
的 length
属性,但是你不应该检查这个属性如果没有匹配,因为它会破坏脚本,所以你必须 if(匹配&& matches.length ...)
。
You can tweak the definition of a word in your regex. The trick is to make use of the length
property of the .match()
, but you should not check this property if there are no matches, since it'll break the script, so you must do if (matches && matches.length ...)
.
此外,修改 X
字样的上述代码非常简单,其中 X
是数字或变量。
Additionally it's quite simple to modify the above code for X
words where X
is either a number or a variable.
jsFiddle example with your 4 examples
这篇关于如何匹配“两个或多个单词”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!