行则将至

人生在勤,不索何获

0%

Multi-line text search in VSCode

原文地址 www.waldo.be

just because I needed it recently – and it made me think of this little gem that I still had to share: what if you have to search over multiple lines in multiple files in VSCode .. something that actually might happen more than you want to admit.

I actually never knew how to do this decently, until I came across this tweet:

1
2
3
4
5
Well… after some digging I found it (literally few moments after my post).

One must use [\s\S\n]+? (at least for CRLF UTF-8 files).
In my case I was searching for all trans-unit occurence with specific source:
<trans-unit id="Enum[\s\S\n]+?</source>
— phenno (@phenno1) October 14, 2021

The core of the “solution” is this RegEx: [\s\S\n]+? 或者 [\s\S\n]*?

To explain you simply:

  • \s: matches any whitespace character (space, table, line breaks)
  • \S: matches any character that is not a whitespace character
  • \n: matches a line feed character (code 10)
  • []: matches any character in this set
  • +: matches one or more of the preceding token – in this case, the set of any character including the line feed
  • ?: causing the preceding quantifier to match as few as possible. So – take all, but as few as you can.

Here are a few examples:

Find all translation-info spread over multiple lines..

<trans-unit id="Enum[\s\S\n]+?<\/source>

Or find “CLEAN19” code snippets with

if not CLEAN19[\s\S\n]+?#endif

And don’t forget to put your search in VSCode in “RegEx” mode (ALT+R)!

Thank you, phenno, for sharing! It might not work for all cases, it might need some finetuning – but for the searches I needed, it always did its job ;-).