.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Sohaib Khalid

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Regular Expression - Quick View

Posted By:Abhinav       Posted Date: February 04, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

Regular Expression - Quick View. Here we will see how to use regular expression in .NET to validate input.

Here we will see how to use regular expression in .NET to validate input.

Regular Expressions Elements:

  • .     Character except a newline character(\n)
  • \d  Any decimal digit
  • \D  Any nondigit
  • \s  Any white-space character
  • \S  Any Non-white-space charater
  • \w Any word character
  • \W Any nonword character
  • ^   Beginning of string or line
  • \A  Beginning of string
  • $   End of string or line
  • \z  End of string
  • |   Matches one of the expressions seprated by the vertical bar; example eee|ttt will match one of eee or ttt (tracing left to right)
  • [abc]   Match with one of the characters; example [rghy] will match r, g,h or c not any other character.
  • [^abc] Match with any of character except in list; example [ghj] will match all character except g,h or k.
  • [a-z] Match any character within specified range; example [a - c] will match a, b or c.
  • ( )  Subexpression treated as a single element by regular expression elements described in this table.
  • ?    Match one or zero occurrences of the previous character or subexpression; example a?b will match a or ab not aab.
  • *   Match zero or more occurences of the previous character or subexpression; example a*b will match b, ab, aab and so on.  
  • +   Match one or more occurences of the previous character or subexpression; example a+b will match ab, aab and so on but not b.
  • {n} Match exactly n occurrences of the preceding character;example a{2} will match only aa.
  • {n,} Match minimum n occurrences of the preceding character;example a{2,} will match only aa,aaa and so on.
  • {n,m} Match minimum n and maximum n occurrences of the preceding character;example a{2, 4} will match aa, aaa, aaaa but not aaaaa.

Example Regular Expression :

  1. Numeric input: ^\d+$  Consists of one or more decimal digits ; example 9 or 9873455.
  2. Credit Card Number: ^\d{4}-?\d{4}-?\d{4}-?\d{4}$
  3. Email Address: \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
  4. UK Postal Code:
    [A-Za-z]{1,2}[0-9R][0-9A-Za-z]? ?[0-9][A-Za-z-[CIKMOVcikmov]]{2}


The most actual regular expression patterns

Pattern Description
^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$ This expression matches email addresses, and checks that they are of the proper form. It checks to ensure the top level domain is between 2 and 4 characters long.
^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$ A regular expression to match phone numbers, allowing for an international dialing code at the start and hyphenation and spaces that are sometimes entered.
^\d{1,2}\/\d{1,2}\/\d{4}$ This regular expressions matches dates of the form XX/XX/YYYY where XX can be 1 or 2 digits long and YYYY is always 4 digits long.
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$ This regular expressions matches time in the format of HH:MM
\b(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5])\b This regular expressions matches Decimal IPs.
^\d{5}$|^\d{5}-\d{4}$ This regular expression will match either a 5 digit ZIP code or a ZIP+4 code formatted as 5 digits, a hyphen, and another 4 digits.
^\d{3}-\d{2}-\d{4}$ This regular expression will match a hyphen-separated Social Security Number (SSN) in the format NNN-NN-NNNN.
^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$ Matches major credit cards including: Visa (length 16, prefix 4), Mastercard (length 16, prefix 51-55), Discover (length 16, prefix 6011), American Express (length 15, prefix 34 or 37). All 16 digit formats accept optional hyphens (-) between each group of four digits.
This regular expression will match some URL.

The conclusion


csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs 

using System.Text.RegularExpressions;
using System;
class Validation
    public static void Main()
        String strToTest;
        Validation objValidate = new Validation();
        Console.Write("Enter a String to Test for Alphabets:");
        strToTest = Console.ReadLine();
        if (objValidate.IsAlpha(strToTest))
            Console.WriteLine("{0} is Valid Alpha String", strToTest);
            Console.WriteLine("{0} is not a Valid Alpha String", strToTest);
    // Function to test for Positive Integers.
    public bool IsNaturalNumber(String strNumber)
        Regex objNotNaturalPattern=new Regex("[^0-9]");
        Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");
        return !objNotNaturalPattern.IsMatch(strNumber) &&objNaturalPattern.IsMatch strNumber);
    // Function to test for Positive Integers with zero inclusive
    public bool IsWholeNumber(String strNumber)
        Regex objNotWholePattern = new Regex("[^0-9]");
        return !objNotWholePattern.IsMatch(strNumber);
    // Function to Test for Integers both Positive & Negative
    public bool IsInteger(String strNumber)
        Regex objNotIntPattern = new Regex("[^0-9-]");
        Regex objIntPattern = new Regex("^-[0-9]+$|^[0-9]+$");
        return !objNotIntPattern.IsMatch(strNumber) &&
    // Function to Test for Positive Number both Integer & Real
    public bool IsPositiveNumber(String strNumber)
        Regex objNotPositivePattern = new Regex("[^0-9.]");
        Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
        Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
        return !objNotPositivePattern.IsMatch(strNumber) &&
        objPositivePattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber);
    // Function to test whether the string is valid number or not
    public bool IsNumber(String strNumber)
        Regex objNotNumberPattern=new Regex("[^0-9.-]");
        Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
        Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
        String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
        String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
        Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + 
        trValidIntegerPattern + ")");
        return !objNotNumberPattern.IsMatch(strNumber) &&!objTwoDotPattern.IsMatchstrNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber);
    // Function To test for Alphabets.
    public bool IsAlpha(String strToCheck)
        Regex objAlphaPattern = new Regex("[^a-zA-Z]");
        return !objAlphaPattern.IsMatch(strToCheck);
    // Function to Check for AlphaNumeric.
    public bool IsAlphaNumeric(String strToCheck)
        Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
        return !objAlphaNumericPattern.IsMatch(strToCheck);

 Subscribe to Articles


Further Readings:

Author: Amit Mehra         Company URL: http://www.dotnetspark.com
Posted Date: February 04, 2010

Good job Abhinav..Short, precise and to the point article...I Like the way you have given sample method to validate using Regular Expression.


Post Comment

You must Sign In To post reply

    Read also another Resources from the same Author

Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend