fun with regular expressions

Posted by Amos Robinson on January 23rd, 2008 filed in ,

Let’s face it, kids. Visual Studio sucks, and so does C#. So we need some sort of secret-weapon against these forces of evil and extra typey-ness, and that’s where vim and regular expressions come in handy.

For the sake of a contrived example, let’s take a boring class called BlogPost:

class BlogPost
{
 public int UserId;
 public DateTime Published;
 public string Title;
 public List<string> Tags;
}

But we don’t really want the raw fields exposed to everyone - and we don’t want to have to type the properties out ourselves.

First off, let’s take a copy of the original fields for use later: select the fields and choose register f with "f (quote f), then yank it with a y (y).
Now we can change those fields to be private, but there’s also a little bit of trickery involved to fit with our naming convention (_lowerCamelCase).

:s/public\(\s.*\s\)\(\w\)\(\w*\)\s*;/private\1_\L\2\E\3;/g

If you’re unfamiliar with vim’s regex syntax, it’s worth noting that \(...\) is equivalent to the perl-ish (...): a capture group. The really cool bit here though is the \L\2\E. For some reason this feature is rarely implemented in other regexes (probably something to do with it not really being regexy…), but it essentially means anything between \L and \E are lowercased after the \2 is expanded. The same is possible with uppercasing: \U\2\E.

Our next step is to create properties from the originals, so let’s get on with that then: paste from register f with "fp, select the pasted properties, and get ready for some magic:

:s/public\(\s.*\s\)\(\w\)\(\w*\s*\);/public\1\2\3\r{\r get { return _\L\2\E\3; }\r set { _\L\2\E\3 = value; }\r}/g

Then, select the code that was outputted and = over it to fix the indentation.

So there you have it! You’ve just converted your fields into properties and getters, now ready for you to manually add nice error checking to them. And, assuming you copied and pasted those regexes, you hopefully did it in less keystrokes than it would otherwise have taken you.


One Response to “fun with regular expressions”

  1. amos Says:

    Postscript: I realised today that the .Net standard library has no sort of stable sorting or stable partitioning. I know I can write them myself, but having used languages like Haskell and C++, the framework’s built-in list operations for .Net seem somewhat lacking. Also, my implementations are undoubtedly going to be far less optimal than an implementation in the framework would be.

Leave a Comment