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.
Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>.+)");
Boolean ismatch = emailregex.IsMatch("johndoe@tempuri.org");
C#
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
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\RegularExpressions\RegexMatch\]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.
|