python - 正则表达式:不在列表中 - Python

标签 python regex regex-negation

有没有一种方法可以让我在表达式中包含检查项目是否不在列表中的能力。

我有一个单词列表的情况:

listA = ["Abc","Def","etc"]

我想做的是在匹配正则表达式的地方执行匹配,但匹配不包含列表中给定的任何单词?

我可以在没有正则表达式的情况下做到这一点,但想知道 Python 中是否有内置的方法来做到这一点。

例如:

names = ["David","John","Bob"]
x = "From John@email.com Sat Jan 5 09:14:16 2008"

y = re.findall([NOT in Names]+'\S+@\S+',x)

预期的输出应该是一个空列表。 (因为它包含约翰) 如果上面的电子邮件是 will@email.com 那么我希望输出是

['will@email.com']

最佳答案

你可以这样做:

names = ["David","John","Bob"]
x = """From will@email.com Sat Jan 5 09:14:16 2008
       From mike@email.com Sat Jan 5 09:14:16 2008"""
y = [m[0] for m in re.findall('((\S+)@\S+)',x) if m[1] not in names]
-> ['will@email.com', 'mike@email.com']

关于python - 正则表达式:不在列表中 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130847/

相关文章:

python - 如何获取 python 数组中的所有 "ids"

python - GUnicorn 提供的 Flask-sockets 并发连接问题

javascript - 将 _wrapper 替换为 html <i> 标签

regex - 在其他行上的两个其他字符串之间查找字符串的所有实例

visual-studio - 如何使用正则表达式否定字符串

regex - 正则表达式不匹配引号中的内容

python - QListView 中的复选框选择

python - 连接错误 SMTP python

php - 匹配字段中的序列化值

regex - 匹配没有任何 2 个连续重复字符的字符串的正则表达式模式