Tuesday, September 29, 2009

Python - simple regular expression examples

# regular expressions are extremely powerful
# here are some simple examples to get you started

import re

text = "Some example text to manipulate with regular expressions."

# find the location of all the vowels
# iterate through all vowels
# here I've used the finditer method to return and
#   and iterator through the results
for i in re.finditer('[aeiouy]', text):
    print "location:", i.start(), " to ", i.end()
    print "  found text was: ", text[i.start():i.end()]
# output:
#location: 1  to  2
#  found text was:  o
#location: 3  to  4
#  found text was:  e
#
# SNIP -- there are lots of vowels
#
#location: 49  to  50
#  found text was:  e
#location: 52  to  53
#  found text was:  i
#location: 53  to  54
#  found text was:  o

# use regular expressions to split your sentence into words
sentence = "This is my example sentence"
for word in re.split(' ', sentence):
    print word
#Output:
# This
# is
# my
# example
# sentence

# search and replace regular expression functionality
# replace 'regular expression' with 're'
text = "regular expression text goes here"
newText = re.sub('regular expression', 're', text)
print newText
#Outputs:
# re text goes here



No comments:

Post a Comment