Click here to Skip to main content
15,867,921 members
Articles / Programming Languages / C#

Regular Expressions in .NET

Rate me:
Please Sign up or sign in to vote.
2.53/5 (16 votes)
17 Dec 2005CPOL5 min read 112.4K   808   38   3
Introduction to regular expressions and how to use them in .NET

Introduction

Regular expressions have been widely popular in languages such as PERL and AWK and have been utilized for pattern matching, text manipulation and text searching. These languages are specifically known for its advanced pattern matching features. .NET regular expressions are based on that of Perl and are compatible with Perl 5 regular expressions.

To begin with, they are not as complex as they look, especially if you start experimenting with them. I would recommend that you download a tool such as Expresso (http://www.ultrapico.com/), to become familiar with regular expressions.

Regular Expression Elements

Some of the commonly used regular expression elements are:

^ Matches start of input
$ Matches end of input
. Matches any character except new line
| OR
* Match the preceding expression 0 or more number of times
+ Match the preceding expression 1 or more number of times
? Match the preceding expression 0 or 1 number of times
() Logical group / sub-expression (capture as auto number group)
(?<name>(exp)) Named capture group
(?=exp) Match any position preceding a suffix exp
(?<=exp) Match any position following a prefix exp
(?!exp) Match any position after which exp is not found
(?<!--exp) Match any position before which exp is not found
[…] List of characters to match
[^expression] Not containing any of the specified character
{n} or {n. m} Quantifier (Match exact number or range of instances)
(?(exp (yes|no)) If expression (exp) is true, match yes part else no part
\ Escape character (to match any of the special characters)
\w Match any word character
\W Match any non-word character
\s Match any white space character
\S Match any non-white space character
\d Match any numeric digit
\D Match any numeric digit
\b Match a backspace if in character matching mode ([]). Otherwise match the position at beginning or end of a word
\t Match tab
\r Match carriage return
\n Match line feed

The following are matching substitutions:

num Substitute last substring matched by group number num
${name} Substitute last substring matched by group name
$& Substitute a copy of entire text itself
$` Substitute all the text of the input string before match
$’ Substitute all the text of the input string after match
$+ Substitute last matched group
$_ Substitute input string
$$ Substitute literal $

Regular expressions could also be used to find repeating patterns by making use of backreferencing, using which you can name a pattern found and then use that reference elsewhere in the expression. This naming of patterns is also useful in case we need to parse a string like free form date or time strings.

Some Example Regular Expressions

  • Match a word - \btest\b
  • Match all 6 letter words - \b\w{6}\b
  • Match all 6 digit numbers - \b\d{6}\b
  • Match any number \b\d+\b

Instead of giving loads of examples here, I suggest that you download Expresso and check its analyzer view for detailed analysis of the regular expression.

Regular Expressions in .NET

As already discussed, .NET regular expressions are based on that of Perl and are compatible with Perl 5 regular expressions. .NET contains a set of powerful classes that makes it even easier to use regular expressions. The classes are available in the System.Text.RegularExpressions namespace. The following is a list of classes in the namespace:

Class Description
Capture Represents the results from a single subexpression capture. Capture represents one substring for a single successful capture.
CaptureCollection Represents a sequence of capture substrings. CaptureCollection returns the set of captures done by a single capturing group.
Group Group represents the results from a single capturing group. A capturing group can capture zero, one, or more strings in a single match because of quantifiers, so Group supplies a collection of Capture objects.
GroupCollection Represents a collection of captured groups. GroupCollection returns the set of captured groups in a single match.
Match Represents the results from a single regular expression match.
MatchCollection Represents the set of successful matches found by iteratively applying a regular expression pattern to the input string.
Regex Represents an immutable regular expression.
RegexCompilationInfo Provides information that the compiler uses to compile a regular expression to a stand-alone assembly.

How to Validate an Input String in .NET

  • Create a Regex object ‘RegexObj
  • Call RegexObj.IsMatch (subjectString), which will return a Boolean showing validity of input string

How to Perform Regular Expression Substitution (Search and Replace) in .NET

  • Create a Regex object ‘RegexObj
  • Call RegexObj.Replace ( subjectString, replaceString ), which will return a Boolean showing validity of input string

How to Parse an Input String in .NET

  • Create a Regex object ‘RegexObj’, make sure to name the expressions
  • Call RegexObj.Match ( subjectString ), which will return a list of matches in the input string as per the match regular expression
  • Iterate through the matches to perform post parsing

Free Form Time Parsing Function in .NET

The following is a utility function that can parse a free format time string. This could be extended to a combined date and time parser along with many more enhancements. If anyone needs further help, feel free to contact me.

C#
private const string TIME_STR = @"^\s?(?" 
           + @"(?\d{1,2})" + @"(:(?\d{1,2}))?"
           + @"\s?((?(am|pm)))?"
           + @")\s?$";

static DateTime ParseTime (string strTime)
{
    DateTime currTime = DateTime.Now;
    DateTime finalTime = DateTime.Today;
    Match m;
    int hour = 0,
    min = 0;
    Regex regExTime = new Regex (TIME_STR, 
        RegexOptions.IgnoreCase
        | RegexOptions.CultureInvariant
        | RegexOptions.IgnorePatternWhitespace
        | RegexOptions.Compiled);

    m = regExTime.Match (strTime);

    if (m.Success)
    {

        if (m.Groups["hour"].Success)
            hour = Int32.Parse (m.Groups["hour"].Value);

        if (m.Groups["min"].Success)
            min = Int32.Parse (m.Groups["min"].Value);

        if (m.Groups["am_pm"].Success) 
            hour = ConvertAmPm (m.Groups["am_pm"].Value, hour);
    } 
    else
        throw new FormatException ("Invalid time format");

    if (hour > 23 || min > 59)
        throw new FormatException ("Invalid time format");

    finalTime = new DateTime (currTime.Year, currTime.Month,
    currTime.Day, hour, min, 0);
    return finalTime;
}

private static int ConvertAmPm (string amPm, int hour)
{
    int retHour = hour;
    amPm = amPm.ToLower();

    if (amPm.Equals("am")) 
    // all hours remain the same except the 12:00 am 
    // (which is 0000 hours)

        if (hour == 12)
            retHour = 00;
        else if (amPm.Equals("pm")) 
        // add 12 to hours except if 12:00 pm

    if (hour != 12)
        retHour = hour + 12;
    else
        throw new FormatException ("Invalid amPm flag format");
    return retHour;
}

Expresso Analysis of the regular expression used above is shown in the figure below. This should help you understand the details.

Image 1

References and Further Reading

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Hong Kong Hong Kong
Ovais Khan is a Software Engineer at Kalsoft (Pvt.) Ltd, where he is working on C# and C++ projects for clients in Pakistan and UAE.

He has done MS (Computer Science). For more details please visit Ovais Khan 's home page and his blog

Comments and Discussions

 
NewsThere's a new version of the RegEx Tester Tool ! Pin
Pablo Osés1-Mar-08 23:31
Pablo Osés1-Mar-08 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.