【问题标题】:Why does my regex in JavaScript return undefined?为什么我在 JavaScript 中的正则表达式返回未定义?
【发布时间】: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


【解决方案1】:

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

你想要简单的( ) 分组。

【讨论】:

  • 谢谢。当我更改为: const regexString = "([^ ]+ ){0,3}" + "test" + "( [^ ]+){0,3}";我得到:['我的','of','the']。有没有办法在“测试”搜索搜索之前和之后捕获几个词?抱歉初学者问题正则表达式让我感到困惑。
  • @Mary 对 - 您的代码期望在 match[1] 中有一些东西,但如果没有真正的捕获组 match 将始终是一个只有一个值的数组。您的代码目前只查看match[1],但正则表达式(固定)捕获两个组,因此您还需要查看match[2]
【解决方案2】:

您应该将非捕获组 (?:...) 包含在捕获组 (...) 中,因为您正在调用捕获组 (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);

【讨论】:

  • 然而,这不会输出关于重叠匹配的正确数据。一种解决方法是使用前瞻结构。
  • 值得一提的是正则表达式doesn't support repeated capturing groups,所以最好的方法是在一个更大的捕获组中捕获三个单词(来自之前和之后)。
  • @RodrigoFerreira 这不是正则表达式,而是味道。即.NET 支持访问量化的捕获组,每个组都是单独的。
猜你喜欢
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 2019-12-20
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
相关资源
最近更新 更多