Remove everything after a particular substring using re.sub

Viewed 4630

I thought this would have been simple, but after 3hrs of trying multiple different re.sub combinations, the answer is still eluding me.

I have the following string:

a = "99999 Anywhere Dr., Roanoak, VA 88888, ,"

I'd like to remove everything between the 88888 and the ending " (note there could be other characters other than space and comma, but there won't be another string of 5 digits after the 88888). I tried many combinations but the closest I got to what I was trying to accomplish was:

re.sub('(?=>\d{5})(.*)\".*$','',a)

This results in "99999" since it doesn't look from the end of the string but instead deletes everything after the first occurrence of the 5 digits. I want the result to be:

"99999 Anywhere Dr., Roanoak, VA 88888"

Thank you

2 Answers

Rather than re.sub, I'd recommend re.search + reassignment:

m = re.search('.*\d{5}', text)
if m:
     text = m.group(0)

print(text)
'99999 Anywhere Dr., Roanoak, VA 88888'
.*        # greedy capture
\d{5}     # 5 digits

If you want to get inventive, you can reverse your string, and then call re.sub, so you look from the start.

text = re.sub('^.*?(?=\d{5})', '', text[::-1])[::-1]
print(text)
'99999 Anywhere Dr., Roanoak, VA 88888'

Reversing the string lets you use a lookahead now, which simplifies things.

^           # start of line
.*?         # non-greedy capture
(?=         # lookahead 
\d{5}       # 5 digits
)

Using re.match:

>>> import re
>>> a = "99999 Anywhere Dr., Roanoak, VA 88888, ,"
>>> re.match(r'^.*[\d{5}]?\d{5}', a).group(0)
'99999 Anywhere Dr., Roanoak, VA 88888'

or re.search:

>>> re.search(r'^.*[\d{5}]?\d{5}', a).group(0)
'99999 Anywhere Dr., Roanoak, VA 88888'
Related