519
%s@{fileID: \(213[0-9]*\)@\='{fileID: '.(submatch(1)-1900)@

I am using this regex search and replace command in vim to subtract a constant from each matching id.

I can do the regex find in VSCode but how can I reference the submatch for maths & replace? submatch(1) does not work in VSCode?

Thanks.

1

10 Answers 10

839

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.

7
  • 3
    asked again diffrently here: stackoverflow.com/questions/35283300/…
    – Rakka Rage
    Commented Feb 9, 2016 at 14:58
  • 12
    I had to replace <p>(.*)</p> with <p>\n\t\t\t\t\t\t$1\n\t\t\t\t\t</p> for a 2000 line file. Imagine me doing it manually. Commented Jun 19, 2019 at 16:40
  • 50
    ... and $0 to reference the full matched string (no parentheses needed). This is useful if you want to add to the search string, as in replacing "Bond" by "$0, James $0".
    – sferencik
    Commented Nov 30, 2020 at 13:56
  • 3
    Dont forget to click the .* button to tell vsc you entering regex
    – Gilbert
    Commented Jan 8, 2021 at 8:42
  • 3
    ~~What if my replacement string has a number right after the reference? E.g. replace (6) with 678? $178 would obviously not work. In some implementations there is a special syntax (${1}78) for that, but at least that one doesn't work in VS Code. Do you happen to know what will?~~ | Nevermind, $178 just magically works! 🤦‍♂️ Commented May 23, 2022 at 15:20
224

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.

4
  • 3
    Very good demonstration of how to use examples to answer questions!
    – Silidrone
    Commented Jul 6 at 9:28
  • This is the comment I've been searching for that's for people not experienced with RegEx. Thank you so much!
    – Tomic
    Commented Jul 24 at 10:21
  • Benjamin got the correct answer to the question that was written but you gave the right answer to the question that was asked! Commented Nov 12 at 14:14
  • Just used this in Cursor (fork of VSCode) and it worked great! I used the parens with a .*, e.g. environment: (.*) and was able to keep the replacement with a environment: $1 while adding a new line of text below my match. Commented Dec 6 at 20:11
130

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: Find and replace

6
  • 18
    for me this works inconsistently - though selection forks correct, the output sometimes keeps $1 without replacement Commented Oct 8, 2018 at 8:26
  • 1
    Hi, @godblessstrawberry, can you share your search and replacement strings? Commented Oct 9, 2018 at 17:49
  • 3
    hi @Diogo I was trying to replace projectwide \[innerHtml\]\s*=\s*"'(.*)'\s*\|\s*translate\s*" with myTranslate="$1" and it was skipping keys randomly and inserting $1 instead of group value sometimes. update to 1.28.0 resolved this issue Commented Oct 10, 2018 at 7:17
  • 1
    @godblessstrawberry, check this: github.com/microsoft/vscode/issues/81825. If it do not apply for you, provide more info and open an issue there. Commented Oct 4, 2019 at 18:33
  • 1
    This regex is a bit dangerous as it won't work when there are multiple img tags in one line or the three letters img appear somewhere in the text. Something like (<img[^>]*)(src=) might be a better solution. Commented Apr 8, 2022 at 10:38
67

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,

  1. 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 as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I 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

1
  • 2
    Honestly, the best answer for beginners such as myself to regex.
    – vchan
    Commented Oct 23, 2020 at 13:23
28

In my case $1 was not working, but $0 works fine for my purpose.

In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!

Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}

Regex Replace String for Laravel Translation

1
  • 1
    Is that possible for you copy your edit your post and copy the code instead of the image? It would be better for visualization.
    – Pankwood
    Commented Dec 13, 2019 at 13:49
13

Just another example for someone figuring out.

In this example, I've added #### to the start of the string and placed the first group $1 after that. Everything outside group (.*) is going to be deleted.

<h4.*">(.*)</h4>
#### $1

enter image description here

# before: 
<h4 id="extract-inline-json-with-regex">Extract inline JSON data with Regex</h4>

# after:
#### Extract inline JSON data with Regex
9

Another simple example:

Search: style="(.+?)"
Replace: css={css`$1`}

Useful for converting HTML to JSX with emotion/css!

0

In "files to include"

./REPONAME/**/{application_stress*,application_k8s*}
./REPONAME/**/application_*{stress*,k8s*}
./REPONAME/**/{*_stress*,*_k8s*}
1
  • Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation? Commented Oct 5, 2023 at 2:55
0

Find: (loadImage([^"]))(.[^"])

Replaces <img [loadImage]="act.landing.image"

and then you can replace if you needed to replace "act.landing.image" Replace: src]=$3

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 6 at 18:32
0

I had the same bug in my vscode and $1 would not fill in the capturing group but literally $1. (I was searching and replacing globally). It seemed that global search was finding results with a "wrong/weird" regex.

I solved it using the following steps:

  1. Test if your regex is working in a specific file first. (using windows ctrl + h)
  2. If your regex is working inside a single file it should work as expected using global search and replace with $1 etc.

In my specific case

  • (formcontrol(?:name)?[^>\n]*)\[disabled\] was giving results in global search but not in a single file.
  • I changed it to (formcontrol(?:name)?(?:[^>]|[\r\n])*)\[disabled\] for it to work in a single file. It then also worked globally.

I hope this helps someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.