Javascript 如何匹配正则表达式中的多个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5421952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:08:44  来源:igfitidea点击:

How to match multiple words in regex

phpjavascriptregexprogramming-languageslookahead

提问by UpHelix

Just a simple regex I don't know how to write.

只是一个简单的正则表达式,我不知道怎么写。

The regex has to make sure a string matches all 3 words. I see how to make it match anyof the 3:

正则表达式必须确保一个字符串匹配所有 3 个单词。我了解如何使其匹配3 个中的任何一个:

/advancedbrain|com_ixxocart|p\=completed/

but I need to make sure that all3 words are present in the string.

但我需要确保所有3 个单词都存在于字符串中。

Here are the words

这里是话

  1. advancebrain
  2. com_ixxocart
  3. p=completed
  1. 超前脑
  2. com_ixxocart
  3. p=完成

回答by Tim Pietzcker

Use lookahead assertions:

使用前瞻断言

^(?=.*advancebrain)(?=.*com_ixxochart)(?=.*p=completed)

will match if all three terms are present.

如果所有三个术语都存在,则将匹配。

You might want to add \bwork boundaries around your search terms to ensure that they are matched as complete words and not substrings of other words (like advancebraindeath) if you need to avoid this:

如果您需要避免这种情况,您可能希望\b在您的搜索词周围添加工作边界以确保它们作为完整的单词而不是其他单词的子字符串(如advancebraindeath)匹配:

^(?=.*\badvancebrain\b)(?=.*\bcom_ixxochart\b)(?=.*\bp=completed\b)

回答by Richard Parnaby-King

^(?=.*?p=completed)(?=.*?advancebrain)(?=.*?com_ixxocart).*$

Spent too long testing and refining =/ Oh well.. Will still post my answer

花了太长时间的测试和改进 =/ 哦,好吧.. 仍然会发布我的答案

回答by Tom

Use lookahead:

使用前瞻:

(?=.*\badvancebrain)(?=.*\bcom_ixxocart)(?=.*\bp=completed)

Order won't matter. All three are required.

顺序无关紧要。这三个都是必需的。