Sunday, July 20, 2008

[.NET] How to Reformat strings with Regular Expressions

.NET has great RegEx support, bad thing is in order to use this features you have to know about regular expressions (or you can just google validation patterns like crazy as I do).

In a recent post we covered how to validate input against a regex pattern How to Validate Strings with RegEx , now we'll see how to reformat strings using Regular Expressions.

Instead of using the System.Text.RegularExpressions.Regex.IsMatch (jeez) method that just checks for a match giving you back a boolean you can use the System.Text.RegularExpressions.Regex.Match (jeez) method which gives you back a match object stuffed with useful crap.

Let'see an example:

//include this statement
using System.Text.RegularExpressions;

//...

string funkyString = "Scuffia likes moby dick";
string reformattedString = "";

//we use round brackets in the reg ex to create groups
Match funkyMatch = Regex.Match(funkyString, @"^(Scuffia) (likes) (moby) (dick)$");

if (funkyMatch.Success)//success property tells us if we have any match
{
reformattedString = String.Format("{0} {1} {2}", funkyMatch.Groups[1], funkyMatch.Groups[2], funkyMatch.Groups[4]);
Console.WriteLine(reformattedString);
}


The output of this example app should read something (exactly) like "Scuffia likes dick".

As discussed above the Match object is being filled with useful stuff. You can access the Success property in order to check if we have any match, if so you can reformat the input string accessing "Groups" - assigned using the round brackets in the regular expression. Notice the group array is zero based but in the first element (index=0) we have the whole matched expression - we can access the actual sub-strings starting from the second element of the Groups array (index = 1).

I must admit, I really suck at regular expressions (I hate them) so my example is really lame, I'll give you that.

Anyway - a couple of days ago Scuffia turned 26 - happy birthday Scuffia!

No comments: