VSCode regex find & replace submatch math?
Given a regular expression of (foobar)
you can reference the first group using $1
and so on if you have more groups in the replace input field.
Just to add another example:
I was replacing src attr in img html tags, but i needed to replace only the src and keep any text between the img declaration and src attribute.
I used the find+replace tool (ctrl+h) as in the image:
To augment Benjamin's answer with an example:
Find Carrots(With)Dip(Are)Yummy
Replace Bananas$1Mustard$2Gross
Result BananasWithMustardAreGross
Anything in the parentheses can be a regular expression.
For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.
So, in case this is your first contact with either:
To find and modify text,
In the "Find" step, you can use regex with "capturing groups," e.g.
I want to find (group1) and (group2)
, using parentheses. This would find the same text asI want to find group1 and group2
, but with the difference that you can then referencegroup1
andgroup2
in the next step:In the "Replace" step, you can refer to the capturing groups via
$1
,$2
etc, so you could change the sentence toI found $1 and $2 having a picnic
, which would outputI found group1 and group2 having a picnic.
Notes:
Instead of just a string, anything inside or outside the
()
can be a regular expression.$0
refers to the whole match