Introduction

A regular expression is a pattern that could be matched against an input text. The following is the important list of regular expressions that we use widely in our applications.

  1. Email id validation
  2. URL validation
  3. Password strength validation
  4. Mobile number validation
  5. String pattern validation

For using a regular expression in C# server side, we need to use the following namespace.

using System.Text.RegularExpressions;

Remember to remove / at the start and the end of the string to convert a JavaScript Regex to C#.

1. Email id validation regular expression

Regular expression:

  1. /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ (Email Id)
  2. /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w- ]+\.)+[\w-]{2,4})?$/ (free/domain specific email id)

2. URL validation regular expression

Regular expression:

  1. /(http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?/ (with or without http)

  2. /((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/( valid everywhere)

3. Password strength validation regular expression

Regular expression:

  1. / ^[a-z0-9\.@#\$%&]+$/ (only contains letter [a-z] digits[0-9], special characters(@#$%&))

  2. / ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/ (Minimum 8 characters at least 1 Alphabet and 1 Number)

  3. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/ (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)

  4. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}/ (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)

  5. / ^[a-zA-Z0-9\s]{7,16}$/ (Minimum length 7 and Maximum length 16 Characters allowed [a–z] [A-Z] [0-9])

4. Mobile number validation regular expression

Regular expression:

  1. / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)

  2. /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)

  3. ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)

5. String pattern validation regular expression

Regular expression:

  1. /(?s)^((?!manish).)*$/ (string contains manish)
  2. \d/ (at list one digit )
  3. /(.)*(\\d)(.)* / (contains number)
  4. /^\d$/ (contains only number )
  5. /^\d{11}$/ (contains only 11 digit number )
  6. /^[a-zA-Z]+$/ (contains only letter )
  7. /^[a-zA-Z0-9]+$/ (contains only letter and number )

Use of the regular expressions

Use the preceding regular expressions in the following ways.

In the following example, I am showing an email validation in various ways. Just replace the regular expression and use any of the others to use another validation.

Using JavaScript

  1. <script type="text/javascript">
  2. function validateEmailId(email) {
  3. var reg = regular expression above pattern
  4. if (reg.test(email)) {
  5. mesg.innerHTML = "";
  6. return true;
  7. }
  8. else {
  9. mesg.style.color = "red";
  10. mesg.innerHTML = "Please provide a valid email address";
  11. return false;
  12. }
  13. }
  14. </script>
Call the preceding method like.

Email Address:
  1. <asp:TextBox ID="txtemail" runat="server" onblur="validateEmailId(this.value)"></asp:TextBox>
  2. <span id="mesg" style="font-size: small; position: relative;">
  3. </span>
Using C# server side

Using a normal function:

ASP.NET

Using RegularExpressionValidator

ASP.NET

Using CustomValidator

ASP.NET
Use regular expression with Linq:

Regex.Match(hrefValue, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$").Success

Using MVC:

Data Annotations

Suppose we have a student class like follows:
  1. public partial class tblstudent
  2. {
  3. public string Studentname { get; set; }
  4. public string Emailid { get; set; }
  5. }
We can apply a regular expression like:
  1. [RegularExpression(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please provide a valid email address")]
  2. public string Emailid { get; set; }
We can also extract a word or group of words from a string using a regular expression.

Suppose we want to extract a domain name and user name from an email id, then by using the following method we can do it.

Using C#:
  1. string hrefValue = txtemail .Text .Trim ();
  2. Match m = Regex.Match(hrefValue, @"^(\w+([-+.']\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$");
  3. Response.Write(string .Format ("UserName : {0}", m.Groups[1].Value));
  4. Response.Write("<br/>");
  5. Response.Write(string.Format("Domain : {0}", m.Groups[3].Value));
Using JavaScript:
  1. <script type="text/javascript">
  2. function validateEmailId(email) {
  3. var reg = /^(\w+([-+.']\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$/;
  4. var matches = email.match(reg);
  5. UserId.innerHTML ='UserName : '+ matches[1];
  6. Domain.innerHTML ='Domain : '+ matches[3];
  7. }
  8. </script>
Email Address:
  1. <asp:TextBox ID="txtemail" runat="server" onblur="validateEmailId(this.value)"></asp:TextBox>
  2. <br/>
  3. <span id="UserId" style="font-size: small; position: relative;"></span>
  4. <br/>
  5. <span id="Domain" style="font-size: small; position: relative;"></span>
We need to make a group inside an expression using ( ) characters and extract that group value using the preceding process. For checking a regular expression click here.

Summary

In this illustration you came to understand the various types of regular expressions and their uses. Here is a detailed tutorial on C# Regex class and its usage, Top C# Regex Code Examples.