Regex C# - how to match methods and properties names of a class

孤街浪徒 提交于 2019-12-13 18:17:52

问题


I want to match methods name (with parameters) and properties name. I dont want to include accessors in match. For example i got this kind of class:

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

For class name I'm using this kind of regex: (?<=class\s)[^\s]+ for methods im trying something like this: [^\s]+(?=() but this will select all that text that has (. For methods i need to select that line that has ( and accessors like public,private and protected. How to do it without including this in final match ? I need only method name and parameters within parenthesis.


回答1:


Edit: Use this 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*)+\)

and get groups named methodName and parameterType and parameter.

Your code can be like this:

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



回答2:


How about using reflection ?

class Program
{
    static void Main(string[] args)
    {
        string assemblyName = Path.Combine(Path.GetTempPath(), string.Format("temp{0}.dll", Guid.NewGuid()));
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CompilerParameters compilerParameters = new CompilerParameters(new string[]
        {
            "System.dll",
            "Microsoft.CSharp.dll",
        }, assemblyName);

        CompilerResults cr = codeProvider.CompileAssemblyFromSource(compilerParameters, File.ReadAllText("Program.cs"));

        if (cr.Errors.Count > 0)
        {
            foreach (CompilerError error in cr.Errors)
            {
                Console.WriteLine(error.ErrorText);
            }
        }
        else
        {
            AppDomain appDomain = AppDomain.CreateDomain("volatile");
            Proxy p = (Proxy)appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Proxy).FullName);
            p.ShowTypesStructure(assemblyName);
            AppDomain.Unload(appDomain);
            File.Delete(assemblyName);
        }
        Console.ReadLine();
    }
}

public class Proxy : MarshalByRefObject
{
    public void ShowTypesStructure(string assemblyName)
    {
        Assembly assembly = Assembly.LoadFrom(assemblyName);
        Type[] types = assembly.GetTypes();
        foreach (Type type in types)
        {
            Console.WriteLine(type.Name);
            MethodInfo[] mis = type.GetMethods();
            foreach (MethodInfo mi in mis)
            {
                Console.WriteLine("\t" + mi.Name);
            }
        }
    }
}



回答3:


It will be rather hard to do this with regular expressions.

You could try creating a proper parser instead. The Irony library is easy to use, and one of the examples is a C# parser.

If you want to use regular expressions, however, you can try using a tool like Expresso, which will help you test and build your regular expression.

You should also write a lot of unit tests - it's rather easy to break something when you modify a regular expression.

Sorry for not providing a "concrete" help, of the kind "use this expression", but I think that if you want to avoid a parser it's really a lot of work :)



来源:https://stackoverflow.com/questions/11643801/regex-c-sharp-how-to-match-methods-and-properties-names-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!