为什么JavaScript中的正则表达式返回undefined?

时间:2018-04-16 22:24:42

标签: javascript regex

我试图找到' 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 ]

为什么我的搜索没有工作?

2 个答案:

答案 0 :(得分:4)

您的代码希望匹配结果包含在正则表达式中捕获组中捕获的内容。但是,您的正则表达式仅包含非捕获组。 (?: )分组明确地捕获匹配的子字符串。

您想要简单的( )分组。

答案 1 :(得分:1)

您应该将非捕获组(?:...)括在捕获组(...)中,因为您正在调用捕获组(match[1])。 :

"((?:\\S+ ){0,3})" + search + "((?: \\S+){0,3})"
  

尝试返回包含前面3个字的数组   继续进行测试'

然后你需要推送两个捕获的组而不是一个:

matches.push([match[1], search, match[2]]);
// `match[1]` refers to first capturing group
// `match[2]` refers to second CG
// `search` contains search word

JS代码:



const search = "test";
const regexString = "((?:\\S+ ){0,3})" + search + "((?: \\S+){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";
while ((match = re.exec(fullText)) != null) {
    matches.push([match[1], search, match[2]]);
}
console.log(matches);