I want to use "Search And Replace" in Visual Studio Code to change every instance of <h1>content</h1>
to #### content
within a document using a Regular Expression.
How can I accomplish that?
This question is related to
regex
visual-studio-code
If you want ex. change all country codes in .json file from uppercase to lowercase:
ctrl+h
alt+r
alt+c
Find: ([A-Z]{2,})
Replace: $1
alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter
ex file:
[
{"id": "PL", "name": "Poland"},
{"id": "NZ", "name": "New Zealand"},
...
]
Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.
For beginners, I wanted to add to the accepted answer, because a couple of subtleties were unclear to me:
To find and modify text (not completely replace),
In the "Find" step, you can use regex with "capturing groups," e.g. your search could be la la la (group1) blah blah (group2)
, using parentheses.
And then in the "Replace" step, you can refer to the capturing groups via $1
, $2
etc.
So, for example, in this case we could find the relevant text with just <h1>.+?<\/h1>
(no parentheses), but putting in the parentheses <h1>(.+?)<\/h1>
allows us to refer to the sub-match in between them as $1
in the replace step. Cool!
Notes
To turn on Regex in the Find Widget, click the .*
icon, or press Cmd/Ctrl
Alt
R
$0
refers to the whole match
Finally, the original question states that the replace should happen "within a document," so you can use the "Find Widget" (Cmd
or Ctrl
+ F
), which is local to the open document, instead of "Search", which opens a bigger UI and looks across all files in the project.
Source: Stackoverflow.com