Friday, March 27, 2009

Regular Experessions - Part 1 - Regex (System.Text.RegularExpressions)

A regular expression is a set of characters that can be compared to a string to determine whether it meets specified format requirements. For validation purposes and to check user inputs, regular expressions are an extremely efficient way.

To use regular expression class and related methods, you need to add its namespace:

using System.Text.RegularExpressions;
...
if (txtRegExp.Text == String.Empty) return;
if (Regex.IsMatch(txtRegExp.Text, @"^\d{3}$"))
MessageBox.Show(String.Format("This strings '{0}' contains 3 digits.",
txtRegExp.Text));
...

In above example regular expression string is "^\d{3}$",
- Leading Caret (^) represent the start of string.
- $ sign represents the end of the string.
- \d means numeric digits.
- {3} indicates three sequential numeric digits.

If you omit leading caret ^ the regular expression would be "\d{3}$" and the expression still matching any string which ending with three digit numbers.
Share/Bookmark

No comments: