Matching Whole Words : sub « Regular Expressions « Python Tutorial






import re

s = '100 BROAD' 
print re.sub('ROAD$', 'RD.', s) 
print re.sub('\\bROAD$', 'RD.', s)              
print re.sub(r'\bROAD$', 'RD.', s)                   
s = '100 BROAD ROAD APT. 3' 
print re.sub(r'\bROAD$', 'RD.', s)                  
print re.sub(r'\bROAD\b', 'RD.', s)








16.7.sub
16.7.1.re.sub substitutes the leftmost, nonoverlapping occurrences of a pattern with a given replacement
16.7.2.Matching at the End of a String
16.7.3.Matching Whole Words
16.7.4.Searching and Replacing with sub() [and subn()]