匹配两个字符串的Javascript正则表达式 [英] Javascript regular expression that matches two strings

查看:102
本文介绍了匹配两个字符串的Javascript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解那么多正则表达式,我想创建一个匹配两个字符串的表达式。

I don't understand that much regular expression and I want to create one that matches two strings.

我知道对于一个字符串,代码是 .match(/ something /)如果两个字符串匹配则为 .match(/ something | someotherthing /)

I know that for one string the code is .match(/something/) and if matches on of two strings it is .match(/something|someotherthing/)

如何编写仅在文本中找到两个字符串时匹配的文本,例如google microsoft

How to write one that only matches when both strings are found in the text e.g "google microsoft"

推荐答案

要使用单个正则表达式执行此操作,您需要考虑到它们可以按任意顺序排列的事实。 (。* 匹配两个子字符串之间的任何字符):

To do it with a single regular expression, you'll need to account for the fact that they could come in either order. (.* matches any characters in between the two substrings):

/google.*microsoft|microsoft.*google/

注意:如果您想要超过2个子串这将失控。 3个字符串可以进入 6 不同的订单,5个字符串可以进入 120 订单,并且可以订购10个子字符串 3628800 不同的方式!这就是为什么使用语言(Javascript)本身的功能,比如Explosion Pills的答案,可能比尝试使用正则表达式做得更好。

Note: If you wanted to do more than 2 substrings this would get out of hand. 3 strings could come in 6 different orders, 5 strings could come in 120 orders, and 10 substrings could be ordered 3628800 different ways! That's why using features of the language (Javascript) itself, like in Explosion Pills answer, can be much better than trying to do too much with a regular expression.

这篇关于匹配两个字符串的Javascript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆