如何匹配“两个或多个单词”

编程入门 行业动态 更新时间:2024-10-24 15:19:26
本文介绍了如何匹配“两个或多个单词”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在给定的字符串中,我试图验证至少有两个单词,其中单词被定义为任何非数字字符,例如

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示例与您的4个示例

jsFiddle example with your 4 examples

更多推荐

如何匹配“两个或多个单词”

本文发布于:2023-10-24 14:48:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   单词   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!