简体   繁体   中英

Get text between capture groups

Suppose I am given a regex like the following:

(\/*).*?(\*/)

Using this regex, I need to transform some text from:

/* This is a comment */

To:

([/*] This is a comment [*/])

Both the regex and the transformation rules are given to me; I can't ask for a different regex format.

I could do this easily if I could reliably split text into a sequence of capture groups and non-captured text. However, this doesn't seem to be possible in general using javascript regexes, because exec does not save information about the indexes of individual matches. Is there a solution?

Use a regexp to transform your regexp by adding additional capture groups:

 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]')); 

Eg using String.prototype.replace() , you can refer the capturing groups by their indices:

 var input = '/* This is a comment */' var output = input.replace(/(\\/\\*)(.*)(\\*\\/)/, '([$1]$2[$3])') console.log(output); // "([/*] This is a comment [*/])" 

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