Question

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?

Was it helpful?

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.");

OTHER TIPS

By providing that you retrieve the codes by line you would get this :

void NameOfTheMethod(string name)

in a varibale named cdLine(for example)

Try using these lines of code

//Get Index of the opening parentheses
int prIndex = cdLine.IndexOf("("); // 20

//Cut the parameter code part
string pmtrString = cdLine.Substring(prIndex + 1); 
pmtrString = pmtrString.Remove(pmtrString.Length - 1);//"string name"//"string name"

//Use this line to check for number of parameters
string[] Parameters = pmtrString.Split(',');

// If it is 1 parameter only like in your example
string[] ParameterParts = pmtrString.Split(' ');// "string", "name"
string ParameterName = ParameterParts[ParameterParts.Length - 1];// "name"

// The ParameterName is the variable containing the Parameter name

Hope this helps

this regex:

(?<=NameOfTheMethod\().+(?=\))

will capture string name if preceeded by NameOfTheMethod( and followed by )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top