简体   繁体   English

匹配两个字符串的Javascript正则表达式

[英]Javascript regular expression that matches two strings

I don't understand that much regular expression and I want to create one that matches two strings. 我不明白那么多正则表达式,我想创建一个匹配两个字符串的表达式。

I know that for one string the code is .match(/something/) and if matches on of two strings it is .match(/something|someotherthing/) 我知道对于一个字符串,代码是.match(/something/) ,如果匹配两个字符串,则为.match(/something|someotherthing/)

How to write one that only matches when both strings are found in the text eg "google microsoft" 如何编写仅在文本中找到两个字符串时才匹配的文件,例如“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/

Note: If you wanted to do more than 2 substrings this would get out of hand. 注意:如果您想要执行2个以上的子串,这将失控。 3 strings could come in 6 different orders, 5 strings could come in 120 orders, and 10 substrings could be ordered 3628800 different ways! 3个字符串可以有6不同的顺序,5个字符串可以有120订单,10个子字符串可以订购3628800不同的方式! 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)本身的功能,比如Explosion Pills的答案,可能比尝试用正则表达式做太多好。

You could just use .match twice 你可以两次使用.match

str.match(/google/) && str.match(/microsoft/)

In that case it may be faster to use .indexOf 在这种情况下,使用.indexOf可能会更快

You can also use a verbose regex 您还可以使用详细的正则表达式

.match(/google.*microsoft|microsoft.*google/)

The other answers are perfectly fine for your specific problem, but as Paulpro noted really get out of hand when you have more than two words. 其他答案对于你的具体问题来说完全没问题,但正如Paulpro指出的那样,当你有两个以上的单词时真的会失控。

The easiest way out is to use multiple checks as Explosion Pills suggests. 最简单的方法是使用Explosion Pills建议的多次检查。

But for a more scalable regex-only approach you can use lookaheads : 但是对于更具可扩展性的正则表达式方法,您可以使用前瞻

/^(?=.*google)(?=.*microsoft)(?=.*apple).../

The lookahead doesn't actually consume anything, so after the first condition is checked (that .*google can match), you are back at the beginning of the string and can check the next condition. 前瞻实际上并没有消耗任何东西,所以在检查完第一个条件后( .*google可以匹配),你回到了字符串的开头,可以检查下一个条件。 The pattern only passes if all lookaheads do. 如果所有前瞻都是这样,那么该模式才会通过。

Note that if your input may contain line breaks, .* will not do. 请注意,如果您的输入可能包含换行符,则.*不会。 You'll have to use [^]* or [\\s\\S]* instead (same goes for the others' answers). 您将不得不使用[^]*[\\s\\S]*代替(其他人的答案也是如此)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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