【问题标题】:Matching and grouping the same part of a string twice using regex?使用正则表达式匹配和分组字符串的相同部分两次?
【发布时间】:2019-08-26 14:57:13
【问题描述】:

这很难用语言来解释,所以也许我可以表明我想要什么。

目前我有以下代码:

  const regex = /(\d?\s\+?\s\d)|(\d?\s\-?\s\d)/g
  const match = '1 + 2 - 7'.match(regex)
  console.log(match)

这会返回两个匹配项:

[ "1 + 2", " - 7" ]

现在,我想知道的是,是否有可能创建一个可以匹配整数2 两次并使其成为两个结果的一部分的正则表达式模式?

期望的输出

[ "1 + 2", "2 - 7" ]

【问题讨论】:

  • 那里总是有 3 个数字?
  • @SnakeEyes 它可以是任意数量的数字,但出于这个问题的目的,我只想知道是否可以使用正则表达式实现我想要的输出。

标签: javascript regex


【解决方案1】:

您可以在positive lookahead 中使用捕获组并使用character class [+-] 来匹配+-

(?=(\d+ [+-] \d+))

图案部分

  • (?=正向前瞻,断言右边是
    • (捕获组1
      • \d+ [+-] \d+ 匹配 1+ 个数字、空格、+ 或 -、空格和 1+ 个数字
    • )关闭群
  • ) 关闭前瞻

Regex demo

请注意,\s 也会匹配换行符。

const regex = /(?=(\d+ [+-] \d+))/g;
const str = `1 + 2 - 7`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  console.log(m[1]);
}

【讨论】:

  • @JossClassey 如果你不使用while循环,你只会得到第一个结果。 This page 可能对 exec 有帮助
  • 感谢您的澄清和出色的回答:)
猜你喜欢
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 2010-09-15
  • 1970-01-01
  • 2012-11-25
  • 2015-10-25
相关资源
最近更新 更多