Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Created December 12, 2023 22:34
Show Gist options
  • Save peteraritchie/cefa006fc491dd8bc451a0527bca96db to your computer and use it in GitHub Desktop.
Save peteraritchie/cefa006fc491dd8bc451a0527bca96db to your computer and use it in GitHub Desktop.
Search and replace try/catch in C#

Search for

^(?'tab'\s*)try\s*\r?\n+\k<tab>\{\r?\n(?'tried'(.*\r?\n)+)\k<tab>\}\r?\n\k<tab>catch\s+.*\r?\n\k<tab>\{\s*\r?\n(?'caught'(.*\r?\n)+)\k<tab>\}(\r?\n)+

Replace with:

${tried}

Given:

        try
        {
            Console.WriteLine("Hello, World!");
        }
        catch (Exception)
        {
            throw;
        }

^(?'tab'\s*)try\s*\r?\n+\k<tab>\{\r?\n finds:

        try
        {

...capturing the tabing in tab (thus matching the { line with the same tabing.)

(?'tried'(.*\r?\n)+)\k<tab>\}\r?\n finds:

            Console.WriteLine("Hello, World!");
        }

... capturing all but the last line (the }.)

\k<tab>catch\s+.*\r?\n\k<tab>\{\s*\r?\n(?'caught'(.*\r?\n)+)\k<tab>\}(\r?\n)+ finds:

        catch (Exception)
        {
            throw;
        }

... matching a catch with the same tabing and capturing the lines between the brackets in caught.


to only replace catches with throw;, replace \k<tab>catch\s+.*\r?\n\k<tab>\{\s*\r?\n(?'caught'(.*\r?\n)+)\k<tab>\}(\r?\n)+ with \k<tab>catch\s+.*\r?\n\k<tab>\{\s*\r?\n(?'caught'(\s+throw;\r?\n))\k<tab>\}(\r?\n)+ or (?'caught'(.*\r?\n)+) with (?'caught'(\s+throw;\r?\n)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment