没有捕获正则表达式中的最后一组

Not capturing last group in regex

我正在使用 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()}`)
  })
}

有没有办法更改正则表达式,使其无需破解即可捕获最后一组?

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

您可以使用 (.+?)(&&|\||;|$) 使用 $ 断言行尾并使用 .+? 匹配除换行符以外的任何字符 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()}`)
  })
}