Thursday, June 10, 2010

Regular Expressions

Here is what I love about regular expressions. They can make your life much easier.
I had to take a list of enumerated values, like this. (The list was a lot longer than shown)
Barbour=1,
Berkeley =2,
Boone =3,
Braxton =4,
Brooke =5,
Cabell =6,
Calhoun =7,
Clay =8,
Doddridge =9,
Fayette =10,
Gilmer =11,
Grant =12,
State=0,
Unknown = 99

and turn it into a switch statements in C# like this...
case 1:
value= LocationID.Barbour;
break;
case 2:
value= LocationID.Berkeley;
break;
case 3:
value= LocationID.Boone;
break;
case 4:
value= LocationID.Braxton;
break;
case 5:
value= LocationID.Brooke;
break;
case 6:
value= LocationID.Cabell;
break;
case 7:
value= LocationID.Calhoun;
break;
case 8:
value= LocationID.Clay;
break;
case 9:
value= LocationID.Doddridge;
break;
case 10:
value= LocationID.Fayette;
break;
case 11:
value= LocationID.Gilmer;
break;
case 12:
value= LocationID.Grant;
break;
case 0:
value= LocationID.State;
break;
case 99:
value= LocationID.Unknown;
break;

I did so using Edit Pad Pro and this search and replace code with Regular expressions
Search:

([a-zA-Z]*)( =)([0-9]*)

Replace:

case \3:
value= LocationID.\1;
break;

Dissecting it, [a-zA-Z] Matches all letters, both upper and lower case, while the asterisk at the end tells it to match all occurrences of it. So "a" and "aaaaaa" would both be a match. The [0-9]* does the same for the code number.

The parentheses separate the search into three terms. The replace using only terms 1 and 3 by specifying a backslash and the term I want (\1 for the first term, \3 for the third term).

The two big advantages are that I don't have to mess with copying and pasting values, which is tedious and time consuming, and I can be sure that I didn't paste the wrong value somewhere.

No comments: