【发布时间】:2018-09-26 18:32:36
【问题描述】:
我正在尝试在我的字符串中找到“test”的所有匹配项:
const search = "test";
const regexString = "(?:[^ ]+ ){0,3}" + "test" + "(?: [^ ]+){0,3}";
const re = new RegExp(regexString, "gi");
const matches = [];
const fullText = "my test string with a lot of tests that should match the test regex";
let match = re.exec(fullText);
while (match != undefined) {
matches.push(match[1]);
match = re.exec(fullText);
}
console.log(matches);
我得到以下信息:
[ undefined, undefined, undefined ]
为什么我的搜索不起作用?
【问题讨论】:
-
预期结果是什么?
-
试图返回一个包含 3 个单词的数组,该数组包含在 'test' 之前并继续进行的 3 个单词
-
澄清一下,如果
exec(..)没有找到匹配项,它将返回null而不是undefined。 -
我不是正则表达式专家,但如果你用matches.push(match[0])替换matches.push(match[1])你会得到:["my test string with a", "lot of test", "应该匹配测试正则表达式"]
标签: javascript regex