Magic of Regex using C#.Net


Regular expression is a compact way of describing complex patterns in texts. You can use them to search for patterns and, once found, to modify the patterns in complex ways. They can also be used to launch programmatic actions that depend on patterns.

 

Regular Expressions offers an extremely powerful way to search, replace, format and extract text data inside a string using sophisticated search criteria. For example, you can search for whole words, or find a match with some pattern (e-mails, phone numbers, postal codes, HTML or XML tags, etc.), and can quickly locate, count, and extract all the occurrences from the searched string.

 

The Regex class also contains several static methods that allow you to use regular expressions without instantiating a Regex object. This reduces the amount of code you have to write, and is appropriate if the same regular expression is used only once or reused seldomly. Note that member overloading is used a lot in the Regex class. All the static methods have the same names (but different parameter lists) as other non-static methods.

Most formalisms provide the following operations to construct regular expressions.

 

Alternation

A vertical bar separates alternatives. For example, "gray|grey" matches gray or grey, which can commonly be shortened to "gr(a|e)y".

 

Grouping

Parentheses are used to define the scope and precedence of the operators. For example, "gray|grey" and "gr(a|e)y" are different patterns, but they both describe the set containing gray and grey.

 

Quantification

A quantifier after a character or group specifies how often that preceding expression is allowed to occur. The most common quantifiers are ?, *, and +:  

  • ?  -  The question mark indicates there is 0 or 1 of the previous expression. For example, "colou?r" matches both color and colour. 
  • *  -  The asterisk indicates there are 0, 1 or any number of the previous expression. For example, "go*gle" matches ggle, gogle, google, etc. 
  • +  -  The plus sign indicates that there is at least 1 of the previous expression. For example, "go+gle" matches gogle, google, etc. (but not ggle).  

These constructions can be combined to form arbitrarily complex expressions, very much like one can construct arithmetical expressions from the numbers and the operations +, -, * and /.

// To enable you to use RegularExpressions
// namespace's Classes like Regex & Match.
using System.Text.RegularExpressions;

Sample code

//Check for correct format of txtFname
Match myMatch = System.Text.RegularExpressions.Regex.Match(txtFname.Text, @"^[A-Z][a-zA-Z]*$");
if (!myMatch.Success)
{
      //First Name was incorrect
      ErrorMessage("Invalid First Name", "Message");
      txtFieldName.Focus();
      return;
}

You can down load the running sample.