Multi-line regular expressions in Visual Studio

Viewed 37958

Is there any way to get Visual Studio to perform a regex replace across multiple lines (let the match cross line boundaries)? I know there are many editors I can use for this, but it seems strange that this feature has been left out of Visual Studio. Am I missing something?

7 Answers

Use (.*\n)*? to skip zero or more lines between your expressions.

start(.*\n)*?end

finds

start
two
three
end

? is the non-greedy operator, used to skip as few lines as possible.

If end is not the first word in the line, add .* to match the extra characters. I.e.: start(.*\n)*?.*end finds

start
two
three
four end end

If you only want to replace until the first end, add another non-greedy operator: start(.*\n)*?.*?end.

Historic: In Visual Studio 2017 (and early versions of 2019) you can also use the single line option in the Find and Replace dialog Ctrl-Shift-F like this:

(?s)start.*end

For more see the version history of this answer.

Non-greedy multi-line any character capture, Visual Studio 2013+:

.*?\r?\n.*?

Greedy version in Giles Roberts's answer.

For everyone coming here while searching for VS Code, I use this to match anything from script to anywhere with 2 newlines (newlines excluded):

script(.|\n)+?(?=\n\n)

replace script and \n\n to match everything between them.

Related