Regular Expressions in C#

RegularExpressions (AKA: Regex) are special strings that define a search pattern. Writing regex in C# is much similar to those you write in python. Some of the important keywords to be learnt before going in for Regex in C# are,

^ – denotes the start of the string
$ – denotes the end of the string
? – zero or one of the preceding element
* – zero or more of the preceding element
+ – one or more of the preceding element
\d – digits
\s – white space
\w – word (characters – including numbers)
\D – non digits
\S – non white space
\W – non word
{m,n} – between m and n times of the preceding element
{n} – n times of the preceding element

For example,

(foo){3} – will be a regex pattern and it will be matching the string “this is a foofoofoo” and it will not match “this is a foo foo foo”.

([+]{1})([\d]{2})-([\d]{2})-([\d]{8}) – will be matching +01-11-12345678

[\s](ROAD) – will be matching only ROAD in “BROAD ROAD” and not BROAD because it expects <whitespace> before “ROAD”

[a-zA-Z]* – will be matching any characters in the set a to z or A to Z, zero or more times

Using Regex in C#

  1. To use Regex in C#, you need a Regex object. So create one from the namespace, System.Text.RegularExpressions
  2. The constructor will take the pattern as string and the option that it needs to put in while doing the pattern matching process.
  3. After creating a Regex object we can search for the pattern in any input strings using the Regex.IsMatch() function. This function takes the input string and returns a boolean value based on the findings.

If you want to get the number of matches, you can use, Regex.Matches() which will return a MatchCollection object. Then to get the number of matches you can use MatchCollection.Count property.

For example,

using System.Text.RegularExpressions;

Regex mySearchPattern = new Regex("([+]{1})([\d]{2})-([\d]{2})-([\d]{8})");

string myInputString = "+01-11-12345678 \n +01-11-87654321";

if(mySearchPattern.IsMatch(myInputString))
{
MatchCollection aCollection = mySearchPattern.Matches(myInputString);
MessageBox.Show(aCollection.Count.ToString());
}

The above snippet will give an output as 2

Tags: ,

One comment

  1. Thanks for this post.
    It has been a cramsheet for me more than once.

    Nice to have such blogs with precise info.
    Keep it up.

Leave a comment