Wednesday, October 2, 2013

Useful Python regular expressions

Regular expressions:

In general we are using expressions to represent common format of a mathematical domain. The term "Regular expression" also engage with a job exactly similar to that. We can see regular standard patterns of strings such as email addresses, phone numbers, ID numbers etc. When we talking about software developing some times we may need to use this formats in order to verify the corresponding insertions of users. That is the place where "Regular expression" plays it's role. we can define a pattern for the day today string patterns in order to verify them.

Regular expression designing is some kind of a art which has a challenge. Following patterns are designed by my self in order to use in python programs.
           

import re

#regular expression to find email addresses ie. sandaru.weerasooriya@gmailcom
regmail = r'(?:[a-z]|[A-Z])+(?:[.]?)(?:[a-z]|[A-Z])+[@][a-z]+[.][a-z]+(?:[^ *])'
founded_mails=re.findall(regmail,"Sandaru.wEerasooriya@gmail.com amalka@gmail.com")
print (founded_mails)
 
#regular expression to identify phonenumbers ie.international and local mobile number formats
regnum = r'[/+]?[0-9][0-9][0-9][-]?[0-9][0-9][0-9][-]?[0-9][0-9][0-9][0-9][0-9]?'
founded_numbers = re.findall(regnum,"071-4969763 077-496-9763 +94714969763 0714969763 0717896678")
print(founded_numbers)

#regular expression to identify only mobitel numbers
regMobitel = r'(?:(?:[/+][9][4][7][1])|(?:[0][7][1][-]?[1-9][1-9]))(?:[0-9][-]?[0-9][0-9][0-9][0-9][0-9]?)'
founded_mobitels = re.findall(regMobitel,"071-4969763 077-496-9763 +94714969763 0714969763")
print(founded_mobitels)

#regular expression to identify only dialog numbers
regDialog = r'(?:(?:[/+][9][4][7][7])|(?:[0][7][7][-]?[1-9][1-9]))(?:[0-9][-]?[0-9][0-9][0-9][0-9][0-9]?)'
founded_dialog = re.findall(regDialog,"071-4969763 077-496-9763 +94714969763 0714969763")
print(founded_dialog)

No comments:

Post a Comment