Web Design that taps into the haromny and vision of your dreams.

Regular Expressions in C#

Demystifying Regular Expressions in C#

Written By on in C#

251 words, estimated reading time 2 minutes.

Regular expressions are special strings that are used to describe a search pattern. They can be used for data validation, data processing and pattern matching.

Regular Expressions (Regex for short) are language and platform independent so an expression for Perl will work on PHP and C#. Regex starts with a caret (^) character and ends with a dollar ($) symbol. The text in between these two characters is used to match a string.

Regular expressions in C# are defined within the System.Text.RegularExpressions namespace which provides a Regex class. When instantiating the class you need to pass the expression string to the constructor. We have used a verbatim string for the regex as it makes the regex easier if you don't have to escape forward slashes.

In this example, we test two strings to see if they contain a valid email address. The emailRegex will match any valid email address.

string ValidEmailAddress = "somebody@somedomain.com";
string InvalidEmailAddress = "invalid.email-address.com&somedomann..3";
string emailRegex = @"^[w-]+(.[w-]+)*@([a-z0-9-]+(.[a-z0-9-]+)*?.[a-z]{2,6}|(d{1,3}.){3}d{1,3})(:d{4})?$";
Regex RegularExpression = new Regex(emailRegex);
if (RegularExpression.IsMatch(ValidEmailAddress))
  Console.WriteLine("{0}: is Valid Email Address", ValidEmailAddress);
  Console.WriteLine("{0}: is NOT a Valid Email Address", ValidEmailAddress);
if (RegularExpression.IsMatch(InvalidEmailAddress))
  Console.WriteLine("{0}: is Valid Email Address", InvalidEmailAddress);
  Console.WriteLine("{0}: is NOT a Valid Email Address", InvalidEmailAddress);

Regular Expressions can be used for input validation, but they can also be used for search and replace functions, extracting values from a string, ASP.Net Input Validation, web.config ISAPI rewrite rules and many other uses.

Last updated on: Friday 23rd June 2017



There are no comments for this post. Be the first!


Leave a Reply

Your email address will not be published.

If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me