Python Regex - Sentence not including strings

痞子三分冷 提交于 2019-12-13 07:34:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!