簡體   English   中英

Python正則表達式-句子不包含字符串

[英]Python Regex - Sentence not including strings

我要嘗試破譯一系列句子。 這是兩個示例:

Valid for brunch on Saturdays and Sundays

Valid for brunch

我想編寫一個正則表達式來標識早午餐一詞,但僅在句子中不包含星期六或星期日的情況下。 如何修改以下正則表達式來做到這一點?

re.compile(r'\bbrunch\b',re.I)
^(?!.*saturday)(?!.*sunday).*(brunch)

您可以通過這種方式嘗試。

https://regex101.com/r/nL5yL3/18

使用列表理解,如果列表中的所有句子都像sentences一樣,則可以使用以下理解:

import re
[re.search(r'\bbranch\b',s) for s in sentences if `saturday` not in s and 'sunday' not in s ]

我會這樣

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM