从磁盘上的 .cs 类文件获取属性

4
我正在为Visual Studio编写一个VSIX扩展。使用这个插件,用户可以从Visual Studio的解决方案资源管理器中选择一个类文件(即磁盘上的实际.cs文件),然后通过触发我的VSIX代码中的上下文菜单项对该文件执行某些操作。
我的VSIX扩展需要知道所选类文件的public和internal属性。
我正在尝试使用正则表达式来解决这个问题,但我卡在了这里。我无法弄清楚如何仅获取类的属性名称。它现在找到了太多。
这是我目前拥有的正则表达式:
\s*(?:(?:public|internal)\s+)?(?:static\s+)?(?:readonly\s+)?(\w+)\s+(\w+)\s*[^(]

演示: https://regex101.com/r/ngM5l7/1 从这个演示中,我想提取所有属性名称:

Brand,
YearModel,
HasRented,
SomeDateTime,
Amount,
Name,
Address

PS. 我知道使用正则表达式并不是处理这种任务的最佳选择。但我认为在VSIX扩展中我没有其他选择。


那么它的预期匹配是什么? - Rahul
这听起来是使用微软编译器服务(Roslyn)的好方法。你为什么认为没有其他选择?我认为获得一个绝不会捕获到误报的可靠正则表达式将极其困难。 - Crowcoder
据我所知,Roslyn编译器需要“有效”的代码。因此,当我提供任何具有对其他类的using语句的类文件时,它也需要加载这些类。它无法仅编译一个位于大型项目中的类文件。@Crowcoder - Vivendi
那么加载整个项目有什么问题呢?这正是内置的智能感知等工具以及像ReSharper这样的工具所做的。它可以解析任意代码块,如果有不可用的引用,则可以获得的内容可能会有所不同。 - Crowcoder
regex101网站不支持.Net风格的正则表达式。我不会相信任何php表达式能在.Net中工作。 - ΩmegaMan
1个回答

3
如何只获取类的属性名称。
这个模式已经被注释了,所以可以使用IgnorePatternWhiteSpace作为一个选项或者将所有注释删除并连接成一行。
但是这个模式会获取你在示例中提供的所有数据。
(?>public|internal)     # find public or internal
\s+                     # space(s)
(?!class)               # Stop Match if class
((static|readonly)\s)?  # option static or readonly and space.
(?<Type>[^\s]+)         # Get the type next and put it into the "Type Group"
\s+                     # hard space(s)
(?<Name>[^\s]+)         # Name found.
  1. 查找六个匹配项(见下文)。
  2. 从命名的匹配捕获组(?<Named> ...)中提取数据,例如mymatch.Groups["Named"].Value或使用硬整数。
  3. 在此情况下,“Type”和“Name”是组名称或索引或使用硬整数。
  4. 会查找注释掉的部分中的模式。

我的工具(为自己创建)报告这些匹配项和组:

Match #0
             [0]:  public string Brand
  ["Type"] → [1]:  string
  ["Name"] → [2]:  Brand

Match #1
             [0]:  internal string YearModel
  ["Type"] → [1]:  string
  ["Name"] → [2]:  YearModel

Match #2
             [0]:  public List<User> HasRented
  ["Type"] → [1]:  List<User>
  ["Name"] → [2]:  HasRented

Match #3
             [0]:  public DateTime? SomeDateTime
  ["Type"] → [1]:  DateTime?
  ["Name"] → [2]:  SomeDateTime

Match #4
             [0]:  public int Amount;
  ["Type"] → [1]:  int
  ["Name"] → [2]:  Amount;

Match #5
             [0]:  public static string Name
  ["Type"] → [1]:  string
  ["Name"] → [2]:  Name

Match #6
             [0]:  public readonly string Address
  ["Type"] → [1]:  string
  ["Name"] → [2]:  Address

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接