2017-05-06 16 views
4

我正在为Visual Studio编写VSIX扩展。使用该插件,用户可以从VS的解决方案资源管理器中选择一个类文件(因此在磁盘上的某个位置实际为.cs文件),然后通过上下文菜单项触发我的VSIX代码,对该文件执行特定操作。从磁盘上的.cs类文件获取属性

我的VSIX扩展需要知道什么publicinternal属性是选定的类文件。

我试图通过使用正则表达式来解决这个问题,但我有点卡住它。我无法弄清楚如何只获取该类的属性名称。它现在发现太多了。

这是正则表达式我到目前为止:

\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扩展选项。

+0

那么什么是它的预期是否匹配? – Rahul

+0

这听起来像是对Microsoft Compiler Services(Roslyn)的很好的使用。你为什么不认为你有其他选择?我认为得到一个永远不会捕获误报的可靠的正则表达式是非常困难的。 – Crowcoder

+0

@Crowcoder据我所知,Roslyn编译器需要“有效”的代码。所以当我给它提供其他类的'using'语句的任何类文件时,它也需要加载它们。它不能编译只存在于一个大项目中的一个类文件。 – Vivendi

回答

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. 在这种情况下,“类型”和“名称”是组名或索引或硬整数。
  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