在Visual Studio的搜索查找/替换中如何使用正则表达式取反

4
我正在为Visual Studios编写查找和替换功能,尝试将所有公共变量更改为具有get/set方法。
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://learn.microsoft.com/en-us/visualstudio/ide/using-regular-expressions-in-visual-studio?view=vs-2019

第二个问题是我正在处理的输出是 $0 { get ; set; }

public string Country; { get; set; }

那么我必须进行第二次查找/替换,以删除分号,因为我无法找到在不获取负匹配的情况下分组分号前面的部分。
我有两个问题:
1) 如何使用正则表达式在VS中忽略事件/委托。
2) 如何获取第一部分的组输出,以便忽略替换中的分号。
非常感谢任何帮助或指导。

尝试使用ROSLYN API,我怀疑它会比RegEx更好。 - Moshe L
^public (?:(?!{|event|delegate)[^=;])*; in VS search and replace tool matches the lines like public string Country; and does not match lines like public event GetUserListCompletedEventHandler GetUserListCompleted; - Wiktor Stribiżew
2
我怀疑你可能使用 ^(public (?:(?!{|event|delegate)[^=;])*); 并替换为 $1 { get; set; }。请查看此正则表达式演示 - Wiktor Stribiżew
1个回答

3
这个正则表达式很棒。它忽略了已经替换过的代码和初始化部分。它还不会捕获末尾的分号,但需要确保它存在。根据评论中的建议,用第一个捕获组替换。我建议把它替换成"$1 { get; set; }"(在不同的正则引擎中可能会有所不同,我不熟悉c#引擎)。
^(public (?!delegate|event)[^=\n{]*(?=;))

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


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