简体   繁体   English

全局查找并替换Visual Studio Code中的换行符

[英]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. 用空字符串替换foo|bar 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. 用空字符串替换(foo|bar)\\n This doesn't actually match anything. 这实际上并不匹配任何东西。

  3. Replace (foo|bar)$ with an empty string. 用空字符串替换(foo|bar)$ 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. 编辑 :好像我的一些文件有Windows行结尾所以(foo|bar)\\r?\\n 确实匹配。 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. foo\\n^(foo|bar)\\n^都有效。

I just tested in my vs code - and you leave the replacement string blank 我刚刚在我的vs代码中测试了 - 你将替换字符串留空了

Yes , it is possible to remove entire lines with the search-across-files feature. 是的 ,可以使用search-across-files功能删除整行。

I'm guessing the original problem was due to a bug or otherwise unwanted behavior in an older version of VSCode. 我猜测原始问题是由于旧版VSCode中的错误或其他不需要的行为造成的。 With VSCode 1.37.1, so long as the \\n is included in the regex, the line is removed. 使用VSCode 1.37.1,只要\\n包含在正则表达式中,就会删除该行。 In particular, the regex (foo|bar)\\n , described in the original question as not working, now works fine. 特别是,在原始问题中描述为不起作用的正则表达式(foo|bar)\\n现在工作正常。

Before: 之前:

更换前截图

After pressing the "Replace All" button: 按“全部替换”按钮后:

更换后的屏幕截图

Related observations: 相关观察:

  • This same regex works even if I set the file line endings to CRLF. 即使我将文件行结尾设置为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. 我查看了搜索配置设置,但似乎没有任何影响这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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