Skip to main content
Email Password   helpLost your password?

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 is known for its advanced pattern matching features. Dot 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)

(?(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 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

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. Dotnet 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

How to perform regular expression substitution (search and replace) in .Net

How to parse an input string in .Net

Free form time parsing function in DotNet

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.

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.

References and Further Reading

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
NewsThere's a new version of the RegEx Tester Tool ! Pin
BucanerO_Slacker
0:31 2 Mar '08  
GeneralExtract From File Path Pin
WDI
23:16 3 Sep '07  
GeneralWingdings??? Pin
dclark
11:37 6 Dec '05  


Last Updated 17 Dec 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009