Search code examples
c#stringdata-extraction

Extracting method arguments from a string in c#


I have a simple file reader which reads through a number of .cs files searching for a specific method which has one parameter. If that method exists, then I want to scrape only the name of the parameter. I was thinking to do a string.Compare(), but then i don't know how to get to the index of the string where the argument starts.

void NameOfTheMethod(string name)
{} 

In this example i want only to scrape out the 'name'.

EDIT: The parameter could also be a const string in some cases. Anyway to bypass that?


Solution

  • You could use a Regex. Something like

    NameOfTheMethod\(.*? (.*?)\)\s*?{

    edit: Testing on your example, this will capture name only (and regardless of whether it's a string, int, object or whatever), not string name

    edit2:

    Complete example:

    //using System.Text.RegularExpressions;
    String input = "void NameOfTheMethod(string name)" + Environment.NewLine + "{}";
    Regex matcher = new Regex(@"NameOfTheMethod\(.*? (.*?)\)\s*?{");
    Match match = matcher.Match(input);
    
    if (match.Success)
        Console.WriteLine("Success! Found parameter name: " + match.Result("$1"));
    else
        Console.WriteLine("Could not find anything.");