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.'
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With