Thom Smith Thom Smith - 1 year ago 58
Javascript Question

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 */


([/*] 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
does not save information about the indexes of individual matches. Is there a solution?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download