Regex negate in Visual Studios search find / replace

Viewed 216

I'm writing a find and replace for Visual Studios and I'm trying to switch all of our public variables to have 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; }

I've been able to get the event/delegate stuff to be ignored in regex, but in Visual Studios the regex parser is barfing when I try to use that code

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

However, this does not work in VS 2019, despite the use of | being valid according to their own document.

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

The second issue is the output I'm doing is $0 { get ; set; }

public string Country; { get; set; }

So then I have to do a second find/replace to change that to remove the ;, because I cannot figure how to group the part before the semicolon, while not getting matches for the negative matches.


So I have two issues

1) How can I get the event/delegates to be ignored using regex in VS

2) How can I get the group for the first section to output, so I ignore the ; in the replace.

Any help or direction is very much appreciated.

1 Answers

How about this regex. It ignores already replaced code and also initialisations. And it also not capturing the semicolon at the end, but demands it to be there. And as suggested in the comment replace with the first capturing group. I suggest it would be "$1 { get; set; }" (could vary between regex engines, i am not familiar with the c# engine)

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

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

Related