Saturday, May 1, 2010

How to write Concise Regular Expression ?

Hello every one!!!

Let's explore the power of regular expression.  As we are aware with that to validate many fields in the forms with specified format  regular expression is great option available with us.
i.e.
  • Phone number(XXX-XXX-XXXX)
  • Email Address
  • URL
  • Date format(dd-MMM-yyyy)
  • Field contains only alpha numerical characters
  • and many more.
 Regular Expression(RE) contains Quantifiers
  • "*" Matches Zero or More
  • "?" Matches Zero or One
  • "+" Matches One or More
"^" & "$" are start and end symbols of RE.
w ----> matches any word character, equivalent to [a-zA-Z0-9]
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9].
\s ----> matches any white space character, equivalent to [\f\n\r\v]
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v]
\d ----> matches any decimal digits, equivalent to [0-9]
\D----> matches any non-digit characters, equivalent to [^0-9]
{4} Specify Number of characters 

Examples:
a) There should not be “1” as first digit,?
^[^1]\d*$ ? this will exclude 1 as first digit.

b) There should not be “1” at any place?
^\d[^1]*$ ? this will exclude the 1 at any place in the sequence.  

c) Date
04-Jan-2010 --> ^\d{2}\-[A-Z][a-z]{2}\-\d{4}

No comments:

Post a Comment