Home > Articles > Programming > C#

📄 Contents

  1. Working with Strings
  2. Working with Regular Expressions
  3. Summary
  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Working with Regular Expressions

Regular expressions allow the fast, efficient processing of text. The text being processed can be something as small as an email address or as large as a multiline input box. The use of regular expressions not only allows you to validate text against a defined pattern, but it also allows you to extract data from text that matches a given pattern.

You can think of a regular expression as an extremely powerful wildcard. Most of us are familiar enough with wildcards to know that when we see an expression like "SAMS *", everything that begins with the word SAMS is a match for that expression. Regular expressions give you additional power, control, and functionality above and beyond simple wildcards.

This section provides you with a brief introduction to the classes in the .NET Framework that support the use of regular expressions. For more information on regular expressions themselves, you might want to check out Regular Expression Pocket Reference (O'Reilly Media, ISBN: 059600415X) or Mastering Regular Expressions, 2nd Edition (O'Reilly Media, ISBN: 0596002890). These books will give you the information you need in order to create your own regular expressions as well as a list of commonly used expressions. Regular expressions themselves are beyond the scope of this chapter.

Validating Input

One extremely common use of regular expressions is to validate user input against some predefined format. For example, rules are often enforced to ensure that passwords have certain characteristics that make them harder to break. These rules are typically defined as regular expressions. Regular expressions are also often used to validate simple input such as email addresses and phone numbers.

The key class provided by the .NET Framework for working with regular expressions is the RegEx class. This class provides a static method called IsMatch that returns a Boolean indicating whether the specified input string matches a given regular expression.

In the following code, a common regular expression used to test for valid email addresses is used:

string emailPattern =
Console.Write("Enter an e-mail address:");
string emailInput = Console.ReadLine();
bool match = Regex.IsMatch(emailInput, emailPattern);
if (match)
    Console.WriteLine("E-mail address is valid.");
    Console.WriteLine("Supplied input is not a valid e-mail address.");

Don't worry if this regular expression doesn't make much sense to you. The basic idea behind the email pattern is that it requires some alphanumeric characters, then an @-sign, and then some combination of characters followed by a ".", and at least two characters following that. Try out the preceding code on different inputs and see what results you get. Even if you don't understand the regular expressions themselves, knowing that they exist and that you can use them to validate input is going to be extremely helpful in the creation of your applications.

Extracting Data from Input

The other common use for regular expressions is in parsing text according to the expression and using that to extract data (called Group matches) from user input.

Regular expressions include a particular feature called groups. A group allows you to put a named identifier on a particular section of the regular expression. When you call Match() to compare input data against the pattern, the results actually separate the matches by group, allowing you to extract the portion of the input that matched each group.

For example, in the preceding example we could have created a group called username that would have allowed us to extract all of the data that precedes the @ symbol in an email address. Then, when performing a match, we could have extracted the username from the input using the regular expression's named group.

Take a look at the following code, which illustrates how to extract both the protocol name and the port number from a URL entered by the user at the console. The great thing about regular expressions is that they are their own language, so they don't have a particular affinity toward C, C++, C#, VB.NET, or any other language. This makes it easy to borrow regular expressions from samples and reference guides on the Internet and in publications. In the following code, the regular expression was borrowed from an MSDN example:

string urlPattern = @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/";
Console.Write("Enter a URL for data parsing: ");
string url = Console.ReadLine();
Regex urlExpression = new Regex(urlPattern, RegexOptions.Compiled);
Match urlMatch = urlExpression.Match(url);
Console.WriteLine("The Protocol you entered was " +
Console.WriteLine("The Port Number you entered was " +

When you run the preceding code against a URL without a port number, you will notice that you don't get any group values. This is because the input doesn't actually match the regular expression at all. When there are no matches, you obviously can't extract meaningful data from the named groups. When you run the preceding code against a URL with port numbers that match the regular expression, you will get output that looks like the following text:

Enter a URL for data parsing: http://server.com:2100/home.aspx
The Protocol you entered was http
The Port Number you entered was :2100
  • + Share This
  • 🔖 Save To Your Account