Using Regular Expressions

Regular expressions are a systematic way of searching, replacing, and parsing text with elaborate patterns of characters. The System.Text.RegularExpressions namespace provides an avenue to the .NET Framework’s regular expression engine. The Regex class is used to compile regular expressions.

Common Methods (Full List)

  • IsMatch – Indicates whether the regular expression finds a match in the input string.
  • Match – Searches an input string for an occurrence of a regular expression and returns the precise result.
  • Matches – Searches an input string for all occurrences of a regular expression and returns all the successful matches.
  • Replace – Within a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.
  • Split – Splits an input string into an array of substrings at the positions defined by a regular expression match.

The Code

Regular Expressions – C# Code Sample

The Result

Regular Expressions can be very complex and there may be several ways to “skin a cat” so to speak. After spending just a couple of minutes surfing the net I found three different patterns for phone numbers.  

^[2-9]\d{2}-\d{3}-\d{4}$ –> 800-555-5555
^(\d{3}-\d{3}-\d{4})*$ –> 555-555-1212
^(\([2-9]|[2-9])(\d{2}|\d{2}\))(-|.|\s)?\d{3}(-|.|\s)?\d{4}$ –> 213-123-1234, 2131231234, (213) 123-1234

There are websites and tools dedicated to the creation of Regular Expressions.  For instance, Roy Osherove is the creator of a tool called RegulazyRegulazy is a visual Regex creation tool for beginners.  There are so many different expression patterns, it is easy to see why there is a need for tools such as this.

More Information

Posted on October 1, 2007, in .NET General. Bookmark the permalink. Leave a Comment.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.