Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrectly Replacing Content

Tags:

python

regex

I'm trying to replace the term brunch in only sentences that contain any of the following words: saturday, sunday and/or weekend. However, it is replacing the entire sentence rather than just the term brunch.

>>> reg = re.compile(r'(?:(?:^|\.)[^.]*(?=saturday|sunday|weekend)[^.]*(brunch)[^.]*(?:\$|\.)|(?:^|\.)[^.]*(brunch)[^.]*(?=saturday|sunday|weekend)[^.]*(?:\$|\.))',re.I)
>>> str = 'Limit 1 per person. Limit 1 per table. Not valid for carryout. Not valid 
    with any other offers, no cash back. Valid only for Wednesday-Friday dinner and 
    Saturday-Sunday brunch. Not valid on federal holidays. Reservation required.'
>>> reg.findall(str)
[('brunch', '')]
>>> reg.sub(r'BRUNCH',str)
'Limit 1 per person. Limit 1 per table. Not valid for carryout. Not valid with any 
 other offers, no cash backBRUNCH Not valid on federal holidays. Reservation required.'

I want it to produce the following:

Limit 1 per person. Limit 1 per table. Not valid for carryout. Not valid with any other
offers, no cash back. Valid only for Wednesday-Friday dinner and Saturday-Sunday BRUNCH. 
Not valid on federal holidays. Reservation required.

Answer:

To solve this I was able to use the following:

>>> reg = re.compile(r'(?:((?:^|\.)[^.]*(?=saturday|sunday|weekend)[^.]*)(brunch)([^.]*(?:\$|\.))|((?:^|\.)[^.]*)(brunch)([^.]*(?=saturday|sunday|weekend)[^.]*(?:\$|\.)))',re.I)
>>> reg.sub('\g<1>BRUNCH\g<3>',str)
'Limit 1 per person. Limit 1 per table. Not valid for carryout. Not valid with any other offers, no cash back. Valid only for Wednesday-Friday dinner and Saturday-Sunday BRUNCH. Not valid on federal holidays. Reservation required.'
like image 716
user2694306 Avatar asked Jul 16 '26 14:07

user2694306


2 Answers

Instead of using a regex, it's simpler to break it down into steps:

s = "Limit 1 per person. Limit 1 per table. Not valid for carryout. Not valid with any other offers, no cash back. Valid only for Wednesday-Friday dinner and Saturday-Sunday brunch. Not valid on federal holidays. Reservation required."
results = []
for line in s.split("."):
    if any(text in line.lower() for text in ("saturday", "sunday", "weekend")):
        results.append(line.replace("brunch", "BRUNCH"))
    else:
        results.append(line)
result = ".".join(results)
print(result)
like image 141
twasbrillig Avatar answered Jul 19 '26 03:07

twasbrillig


Since you're forced to use regex:

Search for

((?:^|\.)(?=[^.]*(?:saturday|sunday|weekend))[^.]*)brunch

replace with

\1BRUNCH

Make sure you compile it as case-insensitive. See demo.

Note that this only replaces one occurence of brunch per sentence.

like image 41
Aran-Fey Avatar answered Jul 19 '26 05:07

Aran-Fey