Click here to Skip to main content
16,016,760 members
Articles / Web Development / ASP.NET

Learn Regular Expressions (RegEx) with Ease

Rate me:
Please Sign up or sign in to vote.
4.92/5 (155 votes)
24 Feb 2014CPOL7 min read 505.2K   348   135
In this article we will try to understand what regex is and how to remember those cryptic syntaxes easily.

Contents

Also view video on regex by clicking below image.

Image 1

So, what’s the agenda?

Regex has been the most popular and easiest way of writing validations. The only big problem with regex has been the cryptic syntax. Developers who are working on projects with complicated validation always refer some kind of cheat sheet to remember the syntaxes and commands.

In this article we will try to understand what regex is and how to remember those cryptic syntaxes easily.

FYI :- This article will use c# language to demonstrate regex implementation , so in case you are using other languages , syntaxes can change accordingly. 

Image 2

You can watch my .NET interview questions and answers videos on various sections like WCF, SilverLight, LINQ, WPF, Design patterns, Entity framework etc.

Just in case if you are new comer, what is regex?

Regex or regular expression helps us describe complex patterns in texts. Once you have described these patterns you can use them to do searching, replacing, extracting and modifying text data.

Below is a simple sample of regex. The first step is to import the namespace for regular expressions.

using System.Text.RegularExpressions;

The next thing is to create the regex object with the pattern. The below pattern specifies to search for alphabets between a-z with 10 length.

Regex obj = new Regex("[a-z]{10}");

Finally search the pattern over the data to see if there are matches. In case the pattern is matching the ‘IsMatch’ will return true.

MessageBox.Show(obj.IsMatch("shivkoirala").ToString());

3 important regex commands

The best way to remember regex syntax is by remembering three things Bracket, caret and Dollars.

Image 3

B

There are 3 types of brackets used in regular expression

Square brackets “[“and Curly “{“ brackets.

Square brackets specify the character which needs to be matched while curly brackets specify how many characters. “(“ for grouping.

We will understand the same as we move ahead in this article.

C caret “^” marks the start of a pattern.^ may appear at the beginning of a pattern to require the match to occur at the very beginning of a line. For example, ^xyz matches xyz123 but not 123xyz. 
D Dollar “$” marks the end of a pattern.$ may appear at the end of a pattern to require the match to occur at the very end of a line. For example, pqr$ matches 123pqr but not pqr123. 

Caret (^) and dollar sign ($) indicate the pattern to the beginning or end of the string being searched.The two anchors may be combined. For example, ^pqr$ matches only pqr. Any characters after or before it will make the pattern invalid.  

Now once you know the above three syntaxes you are ready to write any validation in the world. For instance the below validation shows how the above three entities fit together.  

 Image 4

  • The above regex pattern will only take characters which lies between ‘a’ to ‘z’. The same is marked with square bracket to define the range.
  • The curly bracket's indicates the minimum and maximum length.
  • Finally caret sign at the start of regex pattern and dollar at the end of regex pattern specifies the start and end of the pattern to make the validation more rigid.

So now using the above 3 commands let’s implement some regex validation.


Check if the user has entered shivkoirala?

shivkoirala

Let’s start with the first validation, enter character which exists between a-g?

[a-g]

Enter characters between [a-g] with length of 3?

[a-g]{3}

Enter characters between [a-g] with maximum 3 characters and minimum 1 character?

[a-g]{1,3}

How can I validate data with 8 digit fix numeric format like 91230456, 01237648 etc?

^[0-9]{8}$

How to validate numeric data with minimum length of 3 and maximum of 7, ex -123, 1274667, 87654?

We need to just tweak the first validation with adding a comma and defining the minimum and maximum length inside curly brackets.

^[0-9]{3,7}$


Validate invoice numbers which have formats like LJI1020, the first 3 characters are alphabets and remaining is 8 length number?

First 3 character validation
^[a-z]{3}
8 length number validation
[0-9]{8}


Now butting the whole thing together.

^[a-z]{3}[0-9]{7}$


Check for format INV190203 or inv820830, with first 3 characters alphabets case insensitive and remaining 8 length numeric?

In the previous question the regex validator will only validate first 3 characters of the invoice number if it is in small letters. If you put capital letters it will show as invalid. To ensure that the first 3 letters are case insensitive we need to use ^[a-zA-Z]{3} for character validation.

Below is how the complete regex validation looks like.

^[a-zA-Z]{3}[0-9]{7}$


Can we see a simple validation for website URL’s?

Steps Regex
Step 1 :- Check is www exist
^www.
Step 2 :-The domain name should be atleast 1 character and maximum character will be 15.
. [a-z]{1,15}
Step 3 :-Finally should end with .com or .org
. (com|org)$
^www[.][a-z]{1,15}[.](com|org)$

Let’s see if your BCD works for email validation?

Steps Regex
Step 1 :- Email can start with alphanumeric with minimum 1 character and maximum 10 character. , followed by at the rate (@)
^[a-zA-Z0-9]{1,10}@
Step 2 :-The domain name after the @ can be alphanumeric with minimum 1 character and maximum 10 character , followed by a “.”
[a-zA-Z]{1,10}.
Step 3 :-Finally should end with .com or .org
.(com|org)$
^[a-zA-Z0-9]{1,10}@[a-zA-Z]{1,10}.(com|org)$

Validate numbers are between 0 to 25

^(([0-9])|([0-1][0-9])|([0-2][0-5]))$

Validate a date with MM/DD/YYYY, YYYY/MM/DD and DD/MM/YYYY

Steps

Regex

Description

Let check for DD. First DD has a range of 1-29 ( feb) , 1-30 (small months) , 1-31 (long month) .

So for DD 1-9 or 01-09

[1-9]|0[1-9]

This allow user to enter value between 1 to 9 or 01 to 09.

Now also adding DD check of 10 to 19

[1-9]|1[0-9]

This allows user to enter the value between 01 to 19.

Now adding to above DD check of 20 to 29

[1-9]|1[0-9]|2[0-9]

This allows user to enter the value between 01 to 29.

Now adding to above DD check of 30 to 31

[1-9]|1[0-9]|2[0-9]|3[0-1]

Finally user can enter value between 01 to 31.

Now for seperator it can be a / , -

[/ . -]

This allows user to seperate date by defining seperator.

Now same applying for MM

[1-9]|0[1-9]|1[0-2]

This allow user to enter month value between 01 to 12.

Then for a YY

1[9][0-9][0-9]|2[0][0-9][0-9]

allow user enter the year value between 1900 to 2099.

^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .]([1-9]|0[1-9]|1[0-2])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$ for "DD/MM/YYYY" 

To get MM/DD/YYYY use the following regex pattern.

^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$

And finally to get YYYY/MM/DD use the following regex pattern.

^(1[9][0-9][0-9]|2[0][0-9][0-9])[- / .]([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$

Short cuts

You can also use the below common shortcut commands to shorten your regex validation.

Actual commands Shortcuts
[0-9] \d
[a-z][0-9][_] \w
O or more occurrences *
1 or more occurrences +
0 or 1 occurrence ?

Quick references for regex

Great concise cheat sheet http://www.dijksterhuis.org/csharp-regular-expression-operator-cheat-sheet/

Regex time outfeature in .NET 4.5

The time taken to evaluate a regex expression is directly proportional to the complexity and the number of characters of the regular expression. In simple words if you have many characters it would take more time for parsing.

Image 5

This typical behavior of regex parsing can be exploited by hackers to hang your site forever by making a DOS attack. Below is a nice facebook .NET regex video which demonstrates how regex DOS attack looks like.

Image 6

To overcome this problem in .NET 4.5 they have introduced regex timeout feature, you can read about the same from here

By putting a timeout you can overcome the regex DOS attack.

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
Questionexcellent Pin
kals845-Jul-12 20:30
kals845-Jul-12 20:30 
Questionits so great , Pin
madhuri@mumbai23-May-12 22:52
madhuri@mumbai23-May-12 22:52 
GeneralMy vote of 5 Pin
sravani.v15-May-12 22:02
sravani.v15-May-12 22:02 
GeneralMy vote of 5 Pin
upenn8719-Apr-12 1:53
upenn8719-Apr-12 1:53 
GeneralRegular Expression For Date Format mm-dd-yy Pin
Vedangi10-Apr-12 22:31
Vedangi10-Apr-12 22:31 
GeneralMy vote of 5 Pin
Radhika Khacharia10-Apr-12 21:44
Radhika Khacharia10-Apr-12 21:44 
GeneralMy vote of 5 Pin
Alberto Flores29-Mar-12 5:26
Alberto Flores29-Mar-12 5:26 
GeneralMy vote of 5 Pin
Rajesh Pillai22-Mar-12 23:57
Rajesh Pillai22-Mar-12 23:57 
Nice and easy as usual ShivSmile | :)
GeneralMy vote of 5 Pin
Jαved15-Mar-12 0:36
professionalJαved15-Mar-12 0:36 
GeneralMy vote of 5 Pin
Member 822688125-Jan-12 0:18
Member 822688125-Jan-12 0:18 
GeneralMy vote of 5 Pin
Rob Branaghan9-Dec-11 5:16
Rob Branaghan9-Dec-11 5:16 
GeneralRe: My vote of 5 Pin
Member 106568401-Jun-14 18:33
Member 106568401-Jun-14 18:33 
GeneralMy vote of 5 Pin
Andrey Mazoulnitsyn2-Nov-11 20:40
Andrey Mazoulnitsyn2-Nov-11 20:40 
GeneralMy vote of 5 Pin
SUCHIT S SHAH4-Aug-11 0:30
SUCHIT S SHAH4-Aug-11 0:30 
GeneralMy vote of 5 Pin
Dr.Luiji16-Jul-11 10:37
professionalDr.Luiji16-Jul-11 10:37 
GeneralMy vote of 5 Pin
Anuj Tripathi11-Jul-11 20:28
Anuj Tripathi11-Jul-11 20:28 
GeneralNice Article... Pin
koolprasad200317-Jun-11 21:32
professionalkoolprasad200317-Jun-11 21:32 
GeneralMy vote of 5 Pin
kobymeir8-Jun-11 20:33
kobymeir8-Jun-11 20:33 
GeneralRe: My vote of 5 Pin
Shivprasad koirala9-Jun-11 19:38
Shivprasad koirala9-Jun-11 19:38 
GeneralBug Found in Regex Pin
Ashishmau7-Jun-11 18:36
Ashishmau7-Jun-11 18:36 
GeneralRe: Bug Found in Regex Pin
Shivprasad koirala8-Jun-11 2:32
Shivprasad koirala8-Jun-11 2:32 
GeneralMy 5 Pin
Shahriar Iqbal Chowdhury/Galib7-Jun-11 10:33
professionalShahriar Iqbal Chowdhury/Galib7-Jun-11 10:33 
GeneralRe: My 5 Pin
Shivprasad koirala9-Jun-11 19:37
Shivprasad koirala9-Jun-11 19:37 
Generalnice Pin
BillW337-Jun-11 4:34
professionalBillW337-Jun-11 4:34 
GeneralRe: nice Pin
Shivprasad koirala9-Jun-11 19:38
Shivprasad koirala9-Jun-11 19:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.