Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   |   Class Browser
  |   I want my samples in...   

How Do I...? Common Tasks QuickStart Tutorial

Go To...

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

C# RegexMatch.exe
View Source

[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\RegularExpressions\RegexMatch\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin directory.]




Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.


Hosted by MaximumASP | Found a broken link? | Contact Us | Terms and conditions | Privacy Policy | Advertise with us
� 2000 - 2008  Mindcracker LLC. All Rights Reserved