Search code examples
c#regexvisual-studioresharpervisual-studio-macros

Regex for find all start of method lines in .cs files in visual studio



Want to add some console.writeln's to the first line of every method in my class
(c#, cs file in visual studio 2010). How to identify using Regex so i can search replace?

Before search replace:

void method1(int a)  
{  
}

After search replace:

void method1(int a)  
{  
    console.writeln  
}  

I have resharper too if that helps. Alt up down arrows take you to next prev method start
thank you


Solution

  • It's probably possible to do this with regex for a very limited set of pre-defined method definitions, but probably impossible in the general case. That is, you could easily create a regular expression that matches "void method() {", and some simple variants. But things get complicated very quickly. Imagine this method:

    public static Tuple<int, string, List<Tuple<int, string>>> DoSomething(<arbitrarily complex parameter list>)
    {
    }
    

    You can use regex to get the individual tokens (i.e. "public", "static", etc.), but to determine if something is a method is going to require more parsing logic than you can do with regex only.

    I would suggest that you use ReSharper or some similar tool that can identify the methods for you. Unless you really want to implement a large part of a C# parser.