简体   繁体   中英

Global find and replace with newline in Visual Studio Code

Suppose I want to remove all lines matching a regex in my project. Is there a way to do that?

Using the global find and replace function with regexes enabled I've tried:

  1. Replace foo|bar with an empty string. This doesn't work because it leaves the line there with an empty string. I want the newline removed.

  2. Replace (foo|bar)\\n with an empty string. This doesn't actually match anything.

  3. Replace (foo|bar)$ with an empty string. Again, doesn't match anything.

Any ideas?

Edit : It seems like some of my files have Windows line endings so (foo|bar)\\r?\\n does match. However when you replace it with an empty string it actually still leaves the line endings there.

Here's a test case:

a
foo
b

It should end up like this:

a
b

Not like this:

a

b

foo\\n^ and (foo|bar)\\n^ both work.

I just tested in my vs code - and you leave the replacement string blank

Yes , it is possible to remove entire lines with the search-across-files feature.

I'm guessing the original problem was due to a bug or otherwise unwanted behavior in an older version of VSCode. With VSCode 1.37.1, so long as the \\n is included in the regex, the line is removed. In particular, the regex (foo|bar)\\n , described in the original question as not working, now works fine.

Before:

更换前截图

After pressing the "Replace All" button:

更换后的屏幕截图

Related observations:

  • This same regex works even if I set the file line endings to CRLF.

  • Appending ^ makes no difference. That's a bit surprising, but perhaps "after newline" counts as "beginning of line".

  • Appending $ causes the regex to not match anything. That is quite surprising given the behavior of ^ .

  • I looked through the search configuration settings, but nothing seemed like it could affect this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM