c#regex - 从类文件(.cs)中选择类属性名称,方法名称和字段

bor*_*r4g 5 c# regex methods properties match

我想匹配(从类文件中选择)methodsname,属性名称和字段名称.

这是示例类:

class Perl
{
    string _name;
    public string Name { get; set; }
    public Perl()
    {
    // Assign this._name
    this._name = "Perl";
    // Assign _name
    _name = "Sam";

    // The two forms reference the same field.
    Console.WriteLine(this._name);
    Console.WriteLine(_name);
    }
    public static string doSomething(string test)
    {
        bla test;
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到了方法的代码:

(?:public|private|protected)([\s\w]*)\s+(\w+)\s*\(\s*(?:\w+\s+(\w+)\s*,?\s*)+\)
Run Code Online (Sandbox Code Playgroud)

我有疑问:

  • 以上正则表达式代码获取所有方法,它工作得很好,但我也希望它选择方法名称,但没有参数和访问器.所以从exaplmce类使用我的代码结果将是: public Perl()public static doSomething(string test)但我想要那种结果: Perl()doSomething().所以 - 我的代码匹配良好,但我希望结果显示就像我在上一句中写的那样.
  • 如何选择属性?显示结果:类型和属性名称.所以从exaple类的结果将是:string Name
  • 如何选择带有结果的字段:type field_name.在以下情况下,它将是:string _name

Ria*_*Ria 3

用这个Regex

对于方法

(?:public\s|private\s|protected\s|internal\s)?[\s\w]*\s+(?<methodName>\w+)\s*\(\s*(?:(ref\s|/in\s|out\s)?\s*(?<parameterType>\w+)\s+(?<parameter>\w+)\s*,?\s*)+\)
Run Code Online (Sandbox Code Playgroud)

methodName并获取名为和parameterType的组parameter

对于字段:

(?:public\s|private\s|protected\s)\s*(?:readonly\s+)?(?<type>\w+)\s+(?<name>\w+)
Run Code Online (Sandbox Code Playgroud)

type并获取名为和 的组name

例如,您的方法代码可以如下所示:

var inputString0 = "public void test(string name, out int value)\r\nvoid test(string name, int value)";
foreach (Match match in Regex.Matches(inputString0, @"(?:public\s|private\s|protected\s)?[\s\w]*\s+(?<methodName>\w+)\s*\(\s*(?:(ref\s|/in\s|out\s)?\s*(?<parameterType>[\w\?\[\]]+)\s+(?<parameter>\w+)\s*,?\s*)+\)"))
{
    var methodName = match.Groups["methodName"].Value;
    var typeParameterPair = new Dictionary<string, string>();
    int i = 0;
    foreach (var capture in match.Groups["parameterType"].Captures)
    {
        typeParameterPair.Add(match.Groups["parameterType"].Captures[i].Value, match.Groups["parameter"].Captures[i].Value);
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用codeplex中的Irony - .NET 语言实现工具包