Share via


Finding lines NOT containing certain words - RegEx magic

Regular expressions are full of surprises. Just when you thought you’ve seen it all, out comes a “what if I want to do this, but also that and match these but not those” - and the worse thing is that it is usually my idea in the first place!

So here’s an interesting one: While working on the FxCop reports for our product, I wanted to find (and eventually replace) all public members in the code.
My first thought was this:

 public.*;$

But this expression brought back thousands of false-positives like delegates, events, read-only fields, constants, etc. which are perfectly legal, even under the strict rules of FxCop. I needed something that would filter out the lines that contain certain keywords.

After rummaging the MSDN page for regular expressions and some trial and error I found that the following regular expression did the trick quite nicely, while keeping a good false-positive ratio:

 public ~(const|event|delegate|readonly|static readonly|static extern|abstract).*;$

In English: look for lines with the word public, not followed by any of the words const, event, delegate, etc. and that end with ';'

The rarely used  ~() syntax allows for specifying words that will break the match if found in the specified ___location.

You can also modify the above RegEx to support replacing the faulty line with auto-implemented properties (new in .NET 3.0).

 {public ~(const|event|delegate|readonly|static readonly|static extern|abstract).*};$ 

And use the following string in the “Replace with” field to make an auto-implemented property:

 \1 { get; set; }

A word of warning: Do not run a solution-wide find-replace using this method, as you might break things without noticing. Hand-pick your changes!