Thom Smith Thom Smith - 14 days ago 7
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 */


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?

Answer

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

Comments