简体   繁体   中英

Not capturing last group in regex

I'm using JavaScript regex to split up multiple commands using the separators (&&, ;, |) to determine the boundries of commands. This works well for all except the last command. As a hack I can add a new line to the end of the commands to capture the last group. Here is the code.

 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()}`) }) } 

Is there a way to change the regex so that it will capture the last group without the hack?

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

You could use (.+?)(&&|\\||;|$) using $ to assert the end of the line and use .+? to match any char except a newline 1 or more times to prevent matching an empty string.

If you also want to match a comma you could add that to your alternation.

Note that you are using 2 capturing groups. If you are not using the data from group 2 you could make it non capturing instead (?:

 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()}`) }) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM