Search code examples
regexvisual-studiovisual-studio-2022

Visual Studio replace old code block with new code


I am using Visual Studio 2022 and I want to replace all occurences of a certain if pattern with my new code.

For example these are the situations I want to find:

        if (builder == null)
            throw new ArgumentNullException(nameof(builder));


if (builder == null)
    throw new ArgumentNullException(nameof(builder));

if(builder==null)
    throw new ArgumentNullException(nameof(builder));
    
if (builder == null) {
    throw new ArgumentNullException(nameof(builder));
}
    
if(builder==null) throw new ArgumentNullException(nameof(builder));
    
if (builder == null) throw new ArgumentNullException(nameof(builder));

if(builder==null) {
    throw new ArgumentNullException(nameof(builder));
}

and replace them with

ArgumentNullException.ThrowIfNull(builder);

What I tried is to use the "Find and Replace" build in function of Visual Studio and use a regex to match my search pattern:

if\s*\(\s*([^)]+)\s*==\s*null\s*\)\s*{?\s*throw\s*new\s*ArgumentNullException\s*\(\s*nameof\(\1\)\s*\);\s}?

The problem is, that this works in regex101, but not in Visual Studio.

Here is the regex101: https://regex101.com/r/usKBOk/1

Here is a screenshot of my search settings, trying to see if Visual Studio finds anything: Find in Files


Solution

  • It looks like Visual Studio regex in Find and Replace follows the same rules as Visual Studio Code, and the pattern will never match line breaks with \s or [^()] if there is no \n or \r in the pattern itself.

    In these cases, I'd still suggest a fool-proof solution: Add a \r{0} pattern at the start.

    So, in your case, you can use

    \r{0}if\s*\(\s*([^)]+)\s*==\s*null\s*\)\s*{?\s*throw\s*new\s*ArgumentNullException\s*\(\s*nameof\(\1\)\s*\);\s*}?
    

    Alternative solutions

    • Add \r or \n inside the first positive or even negative(!) character class, e.g. [^)] => [^)\n] or [^)\r]. It is strange for common regex users, but it works in Visual Studio editor and Visual Studio Code. It is not recommendable since testing in online regex tools will not be consistent with the VS results.
    • You may replace the first \s* with [\s\r]* (no need to repeat this with all other occurrences of \s in the pattern since the first one will automatically enable [^)] and \s, and \p{Z}, to match line breaks). This is safe to use since it is consistent with online regex testers.

    Demo screenshot:

    enter image description here