Regular Expressions
  Match a pattern
  Get multiple matches
  Make replacements
  Find common patterns

Get URL for this page

How Do I...Use Regular Expressions to match a pattern?

Regular Expressions allow for easy parsing and matching of strings to a specific pattern. Using the objects available in the RegularExpressions namespace, it is possible to compare a string against a given pattern, replace a string pattern with another string, or to retrieve only portions of a formatted string.

In the simplest case, Regular Expressions can be used to do string comparisons against a pattern of strings. For instance, it can be useful to only allow strings of a particular length range, especially when accepting passwords. The following code demonstrates creating a Regex and testing to see if the string matches the pattern using the IsMatch method.


Dim emailregex As Regex = New Regex("(?<user>[^@]+)@(?<host>.+)");
Dim ismatch As Boolean = emailregex.IsMatch("johndoe@tempuri.org");
VB

This sample illustrates how to create a Regex object using a pattern string. The Match method is called and a Match object is returned. By examining the Success property, the sample decides whether to continue processing the Match object or to print an error message. If the match is successful, the Groups collection of the Match object can be queried for ordinal or named groups within the match. The following sample illustrates using named groups in a pattern match to validate an email address and then print the user and host portions.

Example

 
VB RegexMatch.exe

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.