簡體   English   中英

不捕獲正則表達式中的最后一組

[英]Not capturing last group in regex

我正在使用JavaScript正則表達式使用分隔符(&&,;,|)拆分多個命令,以確定命令的邊界。 這對於除最后一個命令以外的所有命令都適用。 作為一種技巧,我可以在命令末尾添加新行以捕獲最后一個組。 這是代碼。

 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 $ / /(.*?)(&&|\\||;|\\r|$)/gm添加$使其也匹配“行尾”。

您可以使用$來使用(.+?)(&&|\\||;|$)來聲明行尾並使用.+? 匹配除換行符以外的任何char一次或多次,以防止匹配空字符串。

如果您還想匹配逗號,則可以將其添加到替換中。

請注意,您正在使用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()}`) }) } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM