Skip to main content
 首页 » 编程设计

c#之正则表达式 C#之如何匹配类的方法和属性名称

2024年01月25日26lhb25

我想匹配方法名称(带参数)和属性名称。我不想在匹配中包含访问器。 例如我得到了这种类:

public class test 
{ 
    public static string NA = "n/a"; 
 
    public static DateTime DateParser(string dateToBeParsed) 
    { 
        DateTime returnValue = new DateTime(); 
        DateTime.TryParse(dateToBeParsed, GetCulture(), System.Globalization.DateTimeStyles.AssumeLocal , out returnValue); 
        return returnValue; 
    } 
} 

对于类名,我正在使用这种正则表达式:(?<=class\s)[^\s]+ 对于我正在尝试这样的方法:[^\s]+(?=() 但这将选择所有具有 ( 的文本。对于方法,我需要选择具有 ( 和访问器的行像 public、private 和 protected。如果不在最终匹配中包含这个怎么办?我只需要括号内的方法名称和参数。

请您参考如下方法:

编辑:使用此Regex

(?: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*)+\) 

并获取名为 methodName 和 parameterType 和 parameter 的组。

你的代码可以是这样的:

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++; 
    } 
}