【发布时间】: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