MorkaLork Development

Interesting stuff I've picked up over the years...

Using RegEx

2009-04-16 18:00:43 | 206 views | reg regular ex exp expression regularexpression replace

RegExp in C#



If you've used any other programming language you've come across the regexp, or regular expression, method of searching strings. What it means is that you take an expression and use it to search a string, like "find all words that start with 'b' and ends with 's ' (notice the space after s). This often makes things easier, even though regexp is somewhat tricky to master.
For example, say that we have three strings containing the word beer, bear and beor(!?). We want to sort out lines that contains word we don't recognize, and we only know about beer and bear. Beor is some sort of bastard word, and we don't like it =/. Let's see what we can find:

First, we need to add the regexp namespace:



using System.Text.RegularExpressions;


Here is the full code:



using System;
using System.Text.RegularExpressions;

namespace regexp
{
class Program
{
public static void Main(string[] args)
{
//Our strings
string[] strArr = new string[3];
strArr[0] = "There is no more bear!";
strArr[1] = "There is no more beer!";
strArr[2] = "There is not more beor?";

//Our pattern
string pattern = "be[ea]r";

//Our loop ;)
for (int i = 0;i <= 2 ;i++ ) {
if (Regex.IsMatch(strArr[italic], pattern))
{
Console.WriteLine("beer was found!!!");
}
else
{
Console.WriteLine("beer was NOT found...");
}
}
Console.Read();
}
}
}


This will output:

beer was found!
beer was found!
beer was NOT found...


As we can see, we used the same pattern to find both beer and bear. Beor, however, was not found since we didn't look for it, however, with the pattern be[eao]r we would have.

These are the basics of using Regex in C#.


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.