我正在尝试编写此regEx(javascript)来匹配word1和word2(当它存在时):
This is a test. Here is word1 and here is word2, which may or may not exist.
我试过这些:
(word1).*(word2)?
这只会匹配,word1无论是否word2存在.
(word1).*(word2)
这将匹配两者,但仅在两者都存在时才匹配.
我需要一个正则表达式匹配word1和word2 - 可能存在也可能不存在.
Phr*_*ogz 18
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"]
Run Code Online (Sandbox Code Playgroud)
String.prototype.match将对字符串运行正则表达式并找到所有匹配的匹配.在这种情况下,我们使用交替来允许正则表达式匹配word1或word2.
您需要将全局标志应用于正则表达式,以便match()找到所有结果.
如果您只关心字边界的匹配,请使用/\b(?:word1|word2)\b/g.
| 归档时间: |
|
| 查看次数: |
12474 次 |
| 最近记录: |