ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 从磁盘上的.cs类文件中获取属性

2019-06-27 18:02:32  阅读:425  来源: 互联网

标签:c regex net vsix


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

我的VSIX扩展需要知道所选类文件的公共和内部属性.

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

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

\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扩展中的任何其他选项.

解决方法:

how to only get the property names of the class.

此模式已注释,因此请使用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.

>找到六场比赛(见下文).
>从命名匹配捕获(?< Named> …)中提取数据,例如mymatch.Groups [“Named”].值或硬整数.
>在这种情况下,“类型”和“名称”是组名称或索引或具有硬提取.
>将在注释掉的部分中找到模式.

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

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

标签:c,regex,net,vsix
来源: https://codeday.me/bug/20190627/1307418.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有