Validating User Inputs Using Regular Expressions

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-]+$

Using in C#:

  • Namespace of regular expressions : using System.Text.RegularExpressions;
  • Class : Regex;
  • Object : Regex reg = new Regex(string expression);
  • Match Function : reg.IsMatch(string Input) returns bool value.

    True   Input is in correct format[YaaaHooooo].
    False Input is in wrong format[Oh No].

Up Next
    Ebook Download
    View all
    Learn
    View all