Renumber Enums with Regular Expressions

We had a widely-used assembly with an enumeration that did not have explicitly assigned values that was being released from multiple branches and causing problems. In an effort to keep the enumerations synchronized across projects, explicit values were added. The problem is that the values started at 1, whereas the implicit counter starts at 0. The solution is simple: renumber ’em to start at 0. Sounds like a job for regular expressions!

I was really hoping that I could do this using regular expressions in VS2012’s find & replace, but I just couldn’t find a way to implement the necessary arithmetic. After floundering for 15 minutes or so, I decided to just write a simple script in LINQPad. Here’s what I came up with, and it works fantastically.

var filename = @"C:\source\MehType.cs";

var contents = string.Empty;
using (var fs = new FileStream(filename, FileMode.Open))
    using (var sr = new StreamReader(fs))
        contents = sr.ReadToEnd();

var regex = new Regex(@"(.*?= )(\d+)");
foreach (Match match in regex.Matches(contents))
    var num = int.Parse(match.Groups[2].Value);
    contents = contents.Replace(
        match.Value, match.Result("${1}" + --num));

using (var fs = new FileStream(filename, FileMode.Create))
    using (var sw = new StreamWriter(fs))

The result is that this…

public enum MehType
    Erhmm = 1,
    Glurgh = 2,
    Mfhh = 3

…becomes this…

public enum MehType
    Erhmm = 0,
    Glurgh = 1,
    Mfhh = 2

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Renumber Enums with Regular Expressions”

Leave a Reply to Francis Cancel reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: