问题
I have a series of sentences I am trying to decipher. Here are two examples:
Valid for brunch on Saturdays and Sundays
and
Valid for brunch
I want to compose a regex that identifies the word brunch, but only in the case where the sentence does not include the word saturday or sunday. How can I modify the following regex to do this?
re.compile(r'\bbrunch\b',re.I)
回答1:
^(?!.*saturday)(?!.*sunday).*(brunch)
You can try in this way.Grab the capture.See demo.
https://regex101.com/r/nL5yL3/18
回答2:
use a list comprehension , if you have all the sentences in a list like sentences
you can use the following comprehension :
import re
[re.search(r'\bbranch\b',s) for s in sentences if `saturday` not in s and 'sunday' not in s ]
回答3:
I would do like this,
>>> sent = ["Valid for brunch on Saturdays and Sundays", "Valid for brunch"]
>>> sent
['Valid for brunch on Saturdays and Sundays', 'Valid for brunch']
>>> for i in sent:
if not re.search(r'(?i)(?:saturday|sunday)', i) and re.search(r'brunch', i):
print(i)
Valid for brunch
来源:https://stackoverflow.com/questions/27398870/python-regex-sentence-not-including-strings