Tuesday, July 22, 2014

Regular Expressions in Python



This session about Python Regular expressions how we can work with patterns and the specific methods available in re module.

  1. match()
  2. group(), groups()
  3. search()
  4. compile()
  5. sub()

Regular expression sample in Python

Here is the sample for match function use.

#!/usr/bin/python
"""
This program illustrates the usage of match, group functions in re module
This also shows how to use re flags
"""
import re

line = "Python Orientation course helps professionals fish best opportunities"

m = re.match( r'(.*) helps (.*?) .*', line, re.I)

if m:
   print "m.group() : ", m.group()
   print "m.group(1) : ", m.group(1)
   print "m.group(2) : ", m.group(2)
else:
   print "Don't have match!!"
The output
>>> execfile('c:/pybin/rematch.py')
m.group() :  Python Orientation course helps professionals fish best opportunities
m.group(1) :  Python Orientation course
m.group(2) :  professionals

=======

Remove, Replace using re

Example for remove, replace the pattern in the given string
#!/usr/bin/python
import re

DOB = "07-11-1973# This is DOB "

# Delete Python-style comments
num = re.sub(r'#.*$', "", DOB)
print "DOB Num : ", num

# Remove anything other than digits
x = re.sub(r'\D', "", DOB)    
print "DOB without - : ", x


# Substituting other symbol in anything other than digits
FDOB = re.sub(r'\D', "/", num)    
print "DOB in new format : ", FDOB

=======

Searching Pattern

Example for Searching the pattern in a given string

""" This program illustrates is 
 one of the regular expression method i.e., search()"""
import re 
# importing Regular Expression built-in module
text = 'This is my First Regulr Expression Program'
patterns = [ 'first', 'that‘, 'program' ]
# In the text input which patterns you have to search

for pattern in patterns:
    print 'Looking for "%s" in "%s" ->' % (pattern, text),
    if re.search(pattern, text,re.I):
        print 'found a match!'
 # if given pattern found in the text then execute the 'if' condition
    else:
        print 'no match'
 # if pattern not found in the text then execute the 'else' condition
Python Regular Expression

No comments:

Post a Comment

DevOps Foundation course

DevOps Foundation course
Join us to learn DevOps from the Beginning