Using Regular Expressions in C# .Net
Regular Expressions allow for easy parsing and matching of strings to a specific pattern. Using the objects available in the RegularExpressions namespace, you can compare a string against a given pattern, replace a string pattern with another string, or retrieve only portions of a formatted string.
The following example will construct a pattern to validate a e-mail address.
namespace to be used:
using System.Text.RegularExpressions;
Define a new regular expression that will use a pattern match to validate an e-mail address. The following regular expression is structured to accomplish three things:
a. Capture the substring before the @ symbol and put that into the “user” group.
b. Capture the substring after the @ symbol and put that into the “host” group.
c. Make sure that the first half of the string does not have an @ symbol.
Regex emailregex = new Regex(”(?[^@]+)@(?.+)”);
Define a new string containing a valid e-mail address.
String str = “gary@yahoo.com“;
Use the Match method to pass in the e-mail address variable and return a new Match object. The Match object will return regardless of whether any matches were found in the source string.
Match m = emailregex.Match(str);
The success property of the match method is used to continue processing the Match object or to display the error message.
if ( m.Success )
{
Response.Write(”User: ” + m.Groups[”user”].Value);
Response.Write(”Host: ” + m.Groups[”host”].Value);
} else
{
Response.Write(str + ” is not a valid email address”);
}
