查找C#类和方法名称的正则表达式 [英] Regular Expressions to find C# class and method names

查看:163
本文介绍了查找C#类和方法名称的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种影响分析工具,它将分析一堆选定的文件类型,并在文件(在本例中为.cs文件)中查找类和方法调用.我设法编写了一个正则表达式,该表达式将查找代码行是否是方法调用.

I'm writing an impact analysis tool that will parse a bunch of selected file types and find the class and method calls inside the file (in this case a .cs file). I have managed to write a regular expression that will find if a line of code is a method call.

Regex re = new Regex(
               @"\b(public|private|internal|protected)\s*" +
                "(static|virtual|abstract)?\s*[a-zA-Z]*\s[a-zA-Z]+\s*" +
                "\((([a-zA-Z\[\]\<\>]*\s*[a-zA-Z]*\s*)[,]?\s*)+\)");

但是;我不知道如何从正则表达式中获取方法名称.它会将一行识别为Match,但是如何提取实际的方法名称.任何帮助都将是惊人的.

However; I can't figure out how to get the Method name out of the regular expression. It recognises a line as a Match but how do i pull out the actual method name. Any help on this would be amazing.

此外;我不确定这是否实际完成,但是是否有其他(最新的)c#文件解析器能够为我提供文件中方法名称和类名称的列表?

Furthermore; I'm not sure if this is how it's actually done but is there any other (up to date) c# file parsers that will be able to provide me a list of method names and class names from the file?

推荐答案

您可以将表示方法的部分放在

You can put the part that represents a method into a group like this:

(?<method>[a-zA-Z]+)

然后您可以像这样访问它:

Then you can access it like this:

Match match = regex.Match(line);
if (match.Success)
{
    string method = match.Groups["method"].Value;
}

但是,当前的正则表达式在匹配方法名称方面存在各种问题:

However, your regex at the moment has various problems in terms of matching method names:

  • 它不处理泛型(泛型方法,参数或返回值)
  • 它不处理带有数字或_的标识符
  • 它不使用默认访问修饰符处理方法
  • 它将匹配包含看起来像方法声明的东西的字符串文字

要从C#文件中获取方法名称,您确实需要了解C#的内容.请注意,罗斯林(Roslyn)项目很可能使这种事情变得容易得多-我们将很快看到第一个预览发布的时间...

To get method names out of a C# file, you really need something which understands C#. Note that the Roslyn project may well make this sort of thing a lot easier - we'll see when the first preview comes out, very soon now...

这篇关于查找C#类和方法名称的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆