0

I am reading out .cs-files and want to store all parameters per method with at least two parameters. So every two word-combination between paranthesses like follows:

public static void MyFunction(string Param1, int Param2, List<string> Param3)

It should extract string Param1, int Param2 and List<string> Param3 into a collection. There is always a minimum of two parameters when using this.

So far I got the following Regex:

([A-Za-z0-9<>]+\s[a-z0-9]+)

This scans over the entire method header so includes public static as a match too.

Any suggestions on how to fix this?

Thanks.

Roel
  • 754
  • 3
  • 13
  • 30
  • In your application, compile the code from the .cs files and then use reflection to extract the necessary information. The compilation step would also serve as a check whether the code in question is proper C#. See [here](http://stackoverflow.com/questions/7944036/compile-c-sharp-code-in-the-application) or [here](http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments) for further information... –  Jun 20 '15 at 14:19
  • Why are you using regex for this? Parsing code is a solved problem, you don't need to solve it again. You should use [Roslyn](https://github.com/dotnet/roslyn) for this. – Thomas Levesque Jun 20 '15 at 14:47
  • Because there is no need or way to compile this. These are .cs files from multiple projects that are not related in any way. – Roel Jun 20 '15 at 14:49

1 Answers1

1

This just seems much easier to do without using Regex. You'll obviously need something to identify the function header, but once you know you have a function header just break out the parameters like this:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string functionHeader = "public static void MyFunction(string Param1, int Param2, List<string> Param3)";
        string parameters = functionHeader.Substring(functionHeader.IndexOf("(") + 1)
                                          .Replace(", ", ",")
                                          .Replace(")", String.Empty);

        List<string> parametersCollection = new List<string>(parameters.Split(','));
        parametersCollection.ForEach(pc => Console.WriteLine(pc));
    }
}

Results:

string Param1
int Param2
List<string> Param3
Shar1er80
  • 9,001
  • 2
  • 20
  • 29