Thursday, August 20, 2009

The Regular Expressions

As a computer science student, i got my fist introduction to regular expressions(RE) studying "Automata" more properly "Theory of Computer Science" BSCS-501(UoK) :).

To my understanding in one line RE are for pattern matching, the applications of RE varies from search to validations to my knowledge.

When developing web applications i came across some validation problems like credit card, zip codes etc.
For basics of RE the following link will be helpful:

www.regular-expressions.info

www.codeproject.com-Expresso

Use Regular Expressions to Constrain Input in ASP.NET

a very useful utility Expresso


One of the Asp.net validation control RegularExpressionValidator is available now the thing remaining is the "Regular Expression" to validate input, when we view properties of this control more specifically "validationexpression" property in design view there are some available for

US zip code,URl, Email address etc.


On e-commerce website there is a requirnment to validate credit card numbers. i found RE for that from different resources i am sharing both here:

Credit Cards:

All major cards: "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]| [68][0-9])[0-9]{11}|3[47][0-9]{13})$"
American Express: "^3[47][0-9]{13}$"

Discover: ^6011[0-9]{12}$"

MasterCard : "^5[1-5][0-9]{14}$"

Visa : "^4[0-9]{12}(?:[0-9]{3})?$"


Reference: here
to use these RE in code behind Regex Class can be used
like: Regex.IsMatch(CardNumber, "^(51|52|53|54|55)")

Zip Codes:

US/Canada: "\d{5}((-)?\d{4})?|([A-Za-z]\d[A-Za-z]( )?\d[A-Za-z]\d)"

Canada: "[A-Za-z]\d[A-Za-z]( )?\d[A-Za-z]\d"

US: "^\d{5}(-\d{4})?$"

Reference here

Extracting Text from html:

html tags: "<[^>]*>"

Dim strOutput As String = String.Empty
strOutput = System.Text.RegularExpressions.Regex.Replace(input, "<[^>]*>", "")

For More regular expressions visit here , common Regular Expressions

I hope this post might be helpful.








No comments: