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.
这是一个测试。这是word1,这里是word2,可能存在也可能不存在。
I tried these:
我试过这些:
(word1).*(word2)?
This will match only word1
regardless if word2
exists or not.
无论word2是否存在,这都只匹配word1。
(word1).*(word2)
This will match both but only if both exists.
这将匹配两者,但仅在两者都存在时才匹配。
I need a regex to match word1 and word2 - which may or may not exist.
我需要一个正则表达式匹配word1和word2 - 可能存在也可能不存在。
1 个解决方案
#1
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 alternation to 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。
#1
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 alternation to 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。