this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Wednesday, March 3, 2010

Regular Expression in .net

Regular expressions were widely used in the UNIX programming but it can be useful in our higher level language.

We mostly ignore use of Regular expression in our coding due to its very confusing structure but it reduces your many lines of code in to a single statement.

There are so many place where use of regular expression is wise compared to other technique.

Below are some of the lists of it.

à Validating user input

à Compare string with some pattern like zip code, phone number, email address etc.

à Extract specific portion from the user input.

à Replace data on user input when some condition satisfied

To use regular expression in .net you need to import System.Text.RegularExpressions name space in your project.

Regx Class provides many static methods for the play with regular expression.

Below line return Boolean value if input is following phone number pattern (555) 555-5555.

Regex.IsMatch(input, "^\(?\d{3}\)?[\s\-]?\d{3}\-?\d{4}$")

Here number can be any from 0-9.

^ Symbol specifies starting of string.

$ Symbol specifies ending of string.

* Symbol indicates zero or more occurrence of character

? Symbol indicates one occurrence

+ Symbol indicates one or more occurrence

Match method of Regx returns object of Match class. You can extract portion from the input string. Suppose you want to extract each individual number from the above phone number then use below code.

Dim m As Match = Regex.Match(s, "^\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$")

Return String.Format("({0}) {1}-{2}", m.Groups(1), m.Groups(2), m.Groups(3))

There are so many options you can specifies when comparing string against regular expression like you can ignore case, multi line etc.

Go through following regular expression

\d{5}(\-d{4})?$ For zip code 1211,1111-1212 etc.

^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\." & _

"(com|edu|info|gov|int|abc|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$ For Email

^[0-9][0-9]-[0-9][0-9][0-9][0-9]$ For Phone number 11-1234

^[0-9][0-9][0-9][0-9][0-9] [0-9][0-9][0-9][0-9]$ For 1234 1234

^[0-9][0-9][0-9][0-9][0-9] [0-9][0-9][0-9][0-9] RT[0-9][0-9][0-9][0-9]$

For 1234-1234 RT123

^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$ For Zip Code A1A 1A1

No comments: