【问题标题】:Regex negate in Visual Studios search find / replaceVisual Studio 中的正则表达式否定搜索查找/替换
【发布时间】:2020-06-16 07:47:21
【问题描述】:

我正在为 Visual Studios 编写查找和替换,我正在尝试将我们所有的公共变​​量切换为具有 get/sets。

Regex: ^public ((?!({))(?!=).)*;


      //MATCHES CORRECTLY
public string Country;
public string EmailAddress;
public string FirstName;
public string LastName;
public string PhoneNumber;
public string PostalCode;
public string State;
public List<Object> Example;

          //MATCHES BUT SHOULDNT
public event GetUserListCompletedEventHandler GetUserListCompleted;
public delegate void GetUserListCompletedEventHandler(object sender, GetUserListCompletedEventArgs e);

          //DOES NOT MATCH CORRECTLY
throw new Exception("In order to get the public date for blah blah blah");
public List<Order> orderDetails = new List<Order>();        
public string CustomerName { get; set; }
public string BillingAddress1 { get; set; }
public string BillingAddress2 { get; set; }

我已经能够在正则表达式中忽略事件/委托内容,但在 Visual Studios 中,当我尝试使用该代码时,正则表达式解析器会出错

^public ((?!({|event|delegate))(?!=).)*;

但是,这在 VS 2019 中不起作用,尽管使用了 |根据他们自己的文件有效。

https://docs.microsoft.com/en-us/visualstudio/ide/using-regular-expressions-in-visual-studio?view=vs-2019

第二个问题是我正在做的输出是 $0 { 得到 ;放; }

public string Country; { get; set; }

所以我必须进行第二次查找/替换来更改它以删除;,因为我不知道如何对分号之前的部分进行分组,而没有得到否定匹配的匹配项。


所以我有两个问题

1) 如何在 VS 中使用正则表达式忽略事件/代表

2) 如何让第一部分的组输出,所以我忽略 ;在替换中。

非常感谢任何帮助或指导。

【问题讨论】:

  • 尝试使用 ROSLYN API,我怀疑它会比 RegEx 更好。
  • ^public (?:(?!{|event|delegate)[^=;])*; 在 VS 搜索和替换工具中匹配 public string Country; 之类的行,而不匹配 public event GetUserListCompletedEventHandler GetUserListCompleted; 之类的行
  • 我怀疑您可以使用^(public (?:(?!{|event|delegate)[^=;])*); 并替换为$1 { get; set; }。检查this regex demo

标签: c# regex visual-studio visual-studio-2019 regex-negation


【解决方案1】:

这个正则表达式怎么样。它忽略了已经替换的代码和初始化。而且它最后也没有捕获分号,而是要求它在那里。 并按照评论中的建议替换为第一个捕获组。我建议它是“$1 { get; set; }”(正则表达式引擎之间可能会有所不同,我不熟悉 c# 引擎)

^(public (?!delegate|event)[^=\n{]*(?=;))

https://regex101.com/r/VHwmeR/1

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2011-01-08
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多