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)
我有疑问:
用这个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 语言实现工具包。