Multi-line regular expressions in Visual Studio Code

RegexVisual Studio-Code

Regex Problem Overview


I cannot figure a way to make regular expression match stop not on end of line, but on end of file in VS Code? Is it a tool limitation or there is some kind of pattern that I am not aware of?

Regex Solutions


Solution 1 - Regex

It seems the CR is not matched with [\s\S]. Add \r to this character class:

[\s\S\r]+

will match any 1+ chars.

Other alternatives that proved working are [^\r]+ and [\w\W]+.

If you want to make any character class match line breaks, be it a positive or negative character class, you need to add \r in it.

Examples:

  • Any text between the two closest a and b chars: a[^ab\r]*b
  • Any text between START and the closest STOP words:
    • START[\s\S\r]*?STOP
    • START[^\r]*?STOP
    • START[\w\W]*?STOP
  • Any text between the closest START and STOP words:
    • START(?:(?!START)[\s\S\r])*?STOP

See a demo screenshot below:

enter image description here

Solution 2 - Regex

To matcha multi-line text block starting from aaa and ending with the first bbb (lazy qualifier)

aaa(.|\n)+?bbb

To find a multi-line text block starting from aaa and ending with the last bbb. (greedy qualifier)

aaa(.|\n)+bbb

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDima OgurtsovView Question on Stackoverflow
Solution 1 - RegexWiktor StribiżewView Answer on Stackoverflow
Solution 2 - RegexHui ZhengView Answer on Stackoverflow