Friday, November 22, 2013

Python Regular Expressions

Python has a ‘re’ module to handle regular expressions. Here are some examples.
​>>> import re
#Example 1: To extract the contents within double quotes in a string
>>> s = 'customer name is "FirstName LastName"'
>>> re.findall('".*"',s)
​['"FirstName LastName"']               #The result is a list

​#Example 2: To extract the individual words from a combined word like ‘FirstName’
>>> s = 'FirstName'
>>> re.findall('[A-Z][a-z]+',s)
['First', 'Name']  #The result is a list.
>>> ''.join(re.findall('[A-Z][a-z]+',s))
'FirstName'      #To get the string from the list​

​#Example 3: To replace all numbers with a ‘.’ suffix’
>>> s = '1 one 11 eleven'
>>> re.sub("(\d)( )","\\1.\\2",s)
​'1. one 11. eleven'