match.py
replace.py
search.py
############################
# Test Match
############################
## Regex Match
text2 = 'Nov 27, 2012'
import re
if re.match(r'\d+/\d+/\d+', text1): print('yes')
#=> yes
# you can compile the regex for speed
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(text1): print('yes')
#=> yes
## Simple search
text = 'yeah, but no, but yeah, but no, but yeah'
# Exact match
text == 'yeah' #=> False
# Match at start or end
text.startswith('yeah') #=> True
text.endswith('no') #=> False
# Search for the location of the first occurrence
text.find('no') #=> 10
############################
# Replace
############################
# regex
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
#=> 'Today is 2012-11-27. PyCon starts 2013-3-13.'
# simple
text = 'yeah, but no, but yeah, but no, but yeah'
text.replace('yeah', 'yep')
#=> 'yep, but no, but yep, but no, but yep'
###########################
## Extract mathed elements
############################
# extract sub patterns
m = datepat.match('11/27/2012')
( m.group(0), m.group(1), m.group(2), m.group(3))
#=> ('11/27/2012', '11', '27', '2012')
>>> month, day, year = m.groups() # month, day, year is defined
# Find all matches (notice splitting into tuples)
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
datepat.findall(text) #=> [('11', '27', '2012'), ('3', '13', '2013')]