[英]Get text between capture groups
假設我得到如下正則表達式:
(\/*).*?(\*/)
使用此正則表達式,我需要將一些文本轉換為:
/* This is a comment */
至:
([/*] This is a comment [*/])
正則表達式和轉換規則都給了我。 我不能要求其他正則表達式格式。
如果可以將文本可靠地分為一系列捕獲組和未捕獲的文本,則可以輕松完成此操作。 但是,使用javascript正則表達式通常似乎不太可能,因為exec
不會保存有關單個匹配項的索引的信息。 有解決方案嗎?
使用正則表達式通過添加其他捕獲組來轉換正則表達式:
function addCapture(reg) { return new RegExp(reg.source.replace(/\\(.*?\\)|[^(]*/g, match => match[0] === '(' ? match : `(${match})`), reg.flags); } const regexp = /(\\/\\*).*?(\\*\\/)/; const input = "/* This is a comment */"; console.log(input.replace(addCapture(regexp), '[$1]$2[$3]'));
例如,使用String.prototype.replace()
,可以通過捕獲組的索引來引用捕獲組:
var input = '/* This is a comment */' var output = input.replace(/(\\/\\*)(.*)(\\*\\/)/, '([$1]$2[$3])') console.log(output); // "([/*] This is a comment [*/])"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.