546
%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

885

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.

Sign up to request clarification or add additional context in comments.

7 Comments

asked again diffrently here: stackoverflow.com/questions/35283300/…
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.
... 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".
Dont forget to click the .* button to tell vsc you entering regex
~~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! 🤦‍♂️
|
238

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.

5 Comments

Very good demonstration of how to use examples to answer questions!
This is the comment I've been searching for that's for people not experienced with RegEx. Thank you so much!
Benjamin got the correct answer to the question that was written but you gave the right answer to the question that was asked!
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.
There are way too many answers to this and similar questions that do a poor job of actually answering it. This is the only answer that's needed.
134

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 Comments

for me this works inconsistently - though selection forks correct, the output sometimes keeps $1 without replacement
Hi, @godblessstrawberry, can you share your search and replacement strings?
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
@godblessstrawberry, check this: github.com/microsoft/vscode/issues/81825. If it do not apply for you, provide more info and open an issue there.
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.
|
68

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 Comment

Honestly, the best answer for beginners such as myself to regex.
29

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 Comment

Is that possible for you copy your edit your post and copy the code instead of the image? It would be better for visualization.
14

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

Comments

9

Another simple example:

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

Useful for converting HTML to JSX with emotion/css!

Comments

0

In "files to include"

./REPONAME/**/{application_stress*,application_k8s*}
./REPONAME/**/application_*{stress*,k8s*}
./REPONAME/**/{*_stress*,*_k8s*}

1 Comment

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?
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 Comment

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.
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.