javascript 匹配字符串中的任意/所有多个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30114238/
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
Match any/all of multiple words in a string
提问by Azevedo
I'm trying to write this regEx (javascript) to match word1
and word2
(when it exists):
我正在尝试编写这个 regEx (javascript) 来匹配word1
和word2
(当它存在时):
This is a test. Here is word1 and here is word2, which may or may not exist.
This is a test. Here is word1 and here is word2, which may or may not exist.
I tried these:
我试过这些:
(word1).*(word2)?
(word1).*(word2)?
This will match only word1
regardless if word2
exists or not.
这只会匹配,word1
无论是否word2
存在。
(word1).*(word2)
(word1).*(word2)
This will match both but onlyif both exists.
这将匹配两者,但前提是两者都存在。
I need a regex to match word1 and word2 - which may or may not exist.
我需要一个正则表达式来匹配 word1 和 word2 - 这可能存在也可能不存在。
回答by Phrogz
var str = "This is a test. Here is word1 and here is word2, which may or may not exist.";
var matches = str.match( /word1|word2/g );
//-> ["word1", "word2"]
String.prototype.match
will run a regex against the string and find all matching hits. In this case we use alternationto allow the regex to match either word1
or word2
.
String.prototype.match
将对字符串运行正则表达式并找到所有匹配的命中。在这种情况下,我们使用交替来允许正则表达式匹配word1
或word2
。
You need to apply the global flag to the regex so that match()
will find all results.
您需要将全局标志应用于正则表达式,以便match()
找到所有结果。
If you care about matching only on word boundaries, use /\b(?:word1|word2)\b/g
.
如果您只关心单词边界上的匹配,请使用/\b(?:word1|word2)\b/g
.