【问题标题】:Not capturing last group in regex没有在正则表达式中捕获最后一组
【发布时间】:2019-05-03 08:51:30
【问题描述】:

我正在使用 JavaScript 正则表达式来拆分多个命令,使用分隔符(&&、;、|)来确定命令的边界。这适用于除最后一个命令之外的所有命令。作为 hack,我可以在命令末尾添加一个新行来捕获最后一组。这是代码。

const regex = /(.*?)(&&|\||;|\r?\n)/gm
// The EOL is a hack to capture the last command
const test = 'read -p test TEST && echo | ls -lh ~/bin; test | echo\n'
let m

while ((m = regex.exec(test)) !== null) {
  m.forEach((match, groupIndex) => {
    console.log(`Found match, group ${groupIndex}: ${match.trim()}`)
  })
}

有没有办法更改正则表达式,以便在没有 hack 的情况下捕获最后一组?

【问题讨论】:

  • 尝试 (.+?)(&&|\||;|$) 并重复 1 次以上任何字符以防止匹配空字符串。
  • 为什么不在所有分隔符处分割字符串?

标签: javascript regex regex-group


【解决方案1】:

这个正则表达式应该可以解决你的问题:/(.*?)(&&|\||;|\r|$)/gm 添加$ 使其也匹配“行尾”。

【讨论】:

    【解决方案2】:

    您可以使用(.+?)(&&|\||;|$)$ 断言行尾,并使用.+? 匹配除换行符以外的任何字符1 次或多次,以防止匹配空字符串。

    如果您还想匹配逗号,可以将其添加到您的交替中。

    请注意,您正在使用 2 个捕获组。如果您不使用第 2 组的数据,则可以将其设为非捕获 (?:

    const regex = /(.+?)(&&|\||;|$)/gm;
    const test = 'read -p test TEST && echo | ls -lh ~/bin; test | echo\n';
    let m;
    
    while ((m = regex.exec(test)) !== null) {
      m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match.trim()}`)
      })
    }

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2016-04-25
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多