Home > Articles > C# Articles > Learning Regular expression in C#.Net using examples step by step

Learning Regular expression in C#.Net using examples step by step

by Rahul Pyarelal   on Dec 16, 2016   Category: C#  | Level: Intermediate  |  Views: 831    |  Points: 100   
Like this article? Bookmark and Share:
In this article we will Learn Regular expression in C#.Net using examples .

Introduction

Regular expression also called regex.Regular expression helps us to describe complex pattern in texts. Once you define the complex patterns then we can search, validate, replace, extract and modify the text data. A regular expression is an engine of pattern that attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.

Understanding the importance of “[]”, “{}”, “^” and “$” symbol in Regular Expression

[]: - Square brackets specify the characters which need to match what corrector you want in the data.

{}: -To specify the length of the validation we can use the curly brackets for minimum and maximum value. How many characters.

( ): - It’s defining the grouping purpose.

^: - Carrot “^” It is start the regular expression. It’s depending on the multi-line option is set, matches the position before the first character in a line or string.

$: - Dollar “$” it is end of the regular expression. It’s depending on the multi-line option is set, matches the position after the last character in a line or string.

Working of Regular Expression

The regex classes are located in the namespace System.Text.RegularExpressions. To make them available, Import namespace by writing following text under Visual Studio at the start“usingSystem.Text.RegularExpressions;”

usingSystem.Threading.Tasks;
usingSystem.Windows.Forms;
usingSystem.Text.RegularExpressions;

namespaceRegularExperssion
{
publicpartialclassForm1 : Form
    {
public Form1()
        {
InitializeComponent();
        }

privatevoidbtnValidate_Click(object sender, EventArgs e)
        {
Regexobjregular = newRegex(txtPattern.Text);

MessageBox.Show(objregular.IsMatch(txtData.Text).ToString());              
        }
    }
}


1) Regular Expression for validating a website address

I want to validate website address.First put the carrot “^”. It will start with the “www.”, then follow by the Domain name. Domain name can be alphabets, numeric we have also caps alphabets and size is define to curly brackets. After that, we varies domain extension like .com, .in, .org etc. All in the small brackets then end which the $.


For validating of website address we have a regular expression as

^www.[a-z0-9A-Z]{1,20}.(com|org|in)$.

Output


2) Validation for Email

Regular expression magic also works when it comes to validating email addresses,for that use the following expression for the same

^[a-zA-Z0-9]{1,10}@[a-zA-Z]{1,10}.(com|org)$.


Output


3) Validation for Indian Postal Pin code

For validating Indian Postal Pin code use following regular expression


In this code, we limit the pin code character to 6 digit. When you try to put the value more than 6 character to return FALSE. For validating of Indian Pin code, we have a regular expression as ^[0-9]{6}$.

Output


4) Validation for Indian PAN Card number

In order to validate Indian PAN Card number we have to use following image shown condition


In this code, we will validate the PAN number. For validating of Indian Pin code, we have a regular expression as ^[A-Z0-9]{10}$.

Output


5) Validation for Indian mobilenumber

In this part we will demonstrate validating Indian mobile numbers. Some of the format of mobile number which are represented as follows: -

  1. 7894563210
  2. 8974563215
  3. 9685741289
  4. +919940646001
  5. +91-9616274808
  6. 919616247890
  7. 08965239685

All condition is follow by the this code ^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$.


\s -->: Matches any white-space (space, tab, carriage return, line feed) character.

\d -->: Matches any decimal digit (0-9).

?  -->: Repeat 0 or 1 time matching as many times as possible.

Output


6) Validation for date withMM/DD/YYYY format

The format of the date should be represented in format(MM/DD/YYYY) Validation of the date will work and support to above format only rest other will be failed.

The completion validator does a final check to determine whether the input matches a complete date pattern:

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

(|):Matches any one element separated by the vertical bar (|) character.

?:Repeat 0 or 1 time matching as many times as possible.


"Match any string that conforms to this pattern: The first character can be a 0, 1, or 2, and it may be omitted. The second character can be any number and is required. The next character can be a slash or a dash, and is required…”

Output


7) Validation for country code 3 characters (IND):-Group

I want to validate country code three character.In this code, we validate the Country code with three character like IND. We have a regular expression code ^[A-Z]{3}$.


Output


8) Validation for HH/MM/SS format:

When it comes to validate time with this format (HH/MM/SS) then that can also be done using regular expression. Yes you read it correctly, for that use the following regular expression code ^(1[12][1-9]):[0-5][0-9]:[0-5][0-9](\\s)?(?i)(am|pm)$.


Output


There are also other validation for time format

Validation for HH/MM in 24 hrformat:

One more regular expression for displaying time representation which will display time format in 24 hours then for we have anexpression^ ([01]?[0-9]|2[0-3]):[0-5][0-9]$.

9) Validation for range format:

If you want to validaterange here we will consider representing range formatting between (0-100) format, we have a code ^([0-9]|[1-8][0-9]|9[0-9]|100)$.


Output


Hope that above shown and explained 9 various regular expression with their validationwill proveto be useful for you when you come across C# regex.

If you feel tiresome in reading whole article hey there..! You have a choice to learn regular expression from following YouTube video which will be helpful for you. Quickly click on the below play button and enjoy learning it: -



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts