Pages

Sunday, April 10, 2011

Regular Expression in Python

Regular expression is very useful lib, help you so much when you validate email, date time, ... with your conditional expression

to use regular expression you must import module "re"

example:
- we want to check email:

import re

pattern = "\w+@[a-z]+(\.[a-z]+){1,2}"

m = re.compile(pattern)

print m.search("dzeekoo@gmail.com")
print m.search("gmail@gmail")

result:
<_sre.SRE_Match object at 0x01A94E60>
None

----------------------------------------------------------------------------

"." (dot) match any character except new line
"^"(caret) match start of string
"$" match end of string
"*" repeat more than zero time ( >= 0)
"+" repeat more than one (>=1)
"?" if ab? will match for ab and a
{m, n} repeat between m and n times (>=m and <=n)
{m} repeat m times (=m)
{, m} <=m
[] alow ex: [a-z] : allow character from a to z
"|": or ex: a|b if string contain a or b will return true

and more, you can visit http://docs.python.org/library/re.html for more information

0 comments:

Post a Comment