Python正则表达式语句不包括字符串

2024-04-19 17:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的句子要破译。这里有两个例子:

Valid for brunch on Saturdays and Sundays

以及

Valid for brunch

我想编写一个regex来识别单词bunch,但仅限于句子中不包含单词saturday或sunday的情况。如何修改下面的正则表达式来实现这一点?你知道吗

re.compile(r'\bbrunch\b',re.I)

Tags: andreforon单词例子regex句子
3条回答

我想这样做

>>> 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
^(?!.*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 ]

相关问题 更多 >