Visual Studio Code Search and Replace with Regular

2020-05-12 06:24发布

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?

4条回答
做自己的国王
2楼-- · 2020-05-12 06:34

Test it Here: Regex Storm

Example:

Regex: <option value=".*.">|</option>

Text:

<option value="1">Something</option>

Result:

Something

查看更多
该账号已被封号
3楼-- · 2020-05-12 06:36

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),

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses.

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

查看更多
女痞
4楼-- · 2020-05-12 06:38

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ⌥⌘F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-05-12 06:47

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.

查看更多
登录 后发表回答