Using regex in Visual Studio

This is as much a note to self as a blog post :p

One developer in my team had done null == somevariable everywhere in our solution. I think unified code styles are important. So I wanted to remove them. Standard replace does not work here since we need to move the null after the variable name. So we need to use a regex.

Regex

We search for null and then any character as few as possible until we hit a space or a ending parenthesis. We then replace with group 1 ($1) which is the variable name == null and then group 2 ($2) which is either a space or a ending parenthesis.

This ensures above replace works with both if(null == somevar) and code like if(null == somevar && someotherstuff)

Update:
Here is a version on steroids that can do both equals and not equals
Regex v2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s