Regular Expressions (Regex)

Possibly save 1 hour of your time: There are many times where I have to do some sort of pattern matching and then extract certain parameters.

Regex can be helpful in matching some sort of field requirement or even better, it can help extract parameters from the matching pattern.

The Regex object has a Groups property in which if something matches, then the first array element returns the entire matching pattern. And within the pattern you may define multiple groups of patterns and so the second array element will return the first group pattern and third array element will return the second group pattern.

The following are two examples of usage.


[Test]
 public void TestRegex()
 {
 var text = "123-4567890";

//brackets are groups
 var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
 var match = regex.Match(text);

Assert.That(match.Success, Is.True);
 Assert.That(match.Groups[0].Value, Is.EqualTo(text));
 Assert.That(match.Groups[1].Value, Is.EqualTo("123"));
 Assert.That(match.Groups[2].Value, Is.EqualTo("4567890"));
 }

[Test]
 public void TestRegex2()
 {
 var text = "DatasetName='Population',ParameterID=12)";

//* match zero or more times
 //+ match once or more

//brackets are groups
 var regex = new Regex(@",ParameterID=(\d+)");
 var match = regex.Match(text);

Assert.That(match.Success, Is.True);
 Assert.That(match.Groups[0].Value, Is.EqualTo(",ParameterID=12"));
 Assert.That(match.Groups[1].Value, Is.EqualTo("12"));

 }
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s