Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex match and replace multiple patterns

Tags:

python

regex

I have a situation where a user submits an address and I have to replace user inputs to my keys. I can join this using an address without suffixes.

COVERED WAGON TRAIL

CHISHOLM TRAIL

LAKE TRAIL

CHESTNUT ST

LINCOLN STREET

to:

COVERED WAGON

CHISHOLM

LAKE

CHESTNUT

LINCOLN

However I can't comprehend how this code can be written to replace only the last word. I get:

LINCOLN

CHESTNUT

CHISHOLM

LAKEAIL

CHISHOLMAIL

COVERED WAGONL

I've tried regex verbose, re.sub and $.

import re
target = '''

LINCOLN STREET
CHESTNUT ST
CHISHOLM TR
LAKE TRAIL
CHISHOLM TRAIL
COVERED WAGON TRL

'''
rdict = {
' ST': '',
' STREET': '',
' TR': '',
' TRL': '',
}
robj = re.compile('|'.join(rdict.keys()))
re.sub(' TRL', '',target.rsplit(' ', 1)[0]), target
result = robj.sub(lambda m: rdict[m.group(0)], target)
print result
like image 268
George Avatar asked Aug 07 '13 01:08

George


1 Answers

Use re.sub with $.

target = '''
LINCOLN STREET
CHESTNUT ST
CHISHOLM TR
LAKE TRAIL
CHISHOLM TRAIL
COVERED WAGON TRL
'''

import re
print re.sub('\s+(STREET|ST|TRAIL|TRL|TR)\s*$', '', target, flags=re.M)
like image 141
falsetru Avatar answered Sep 22 '22 21:09

falsetru