python - 正则表达式匹配键,除了一个

标签 python regex

我有一个Python列表。它包含类似 items[number].some field 的字符串。我想要获取除匹配 items[<number>].classification 的字符串之外的所有字符串。我如何通过正则表达式来做到这一点,或者也许还有其他方法?

举个例子,我有这样的东西:

data.items.[0].deliveryAddress.region

data.items.[0].classification.scheme

data.items.[0].classification.id

data.items.[0].description

我只想和:

data.items.[0].description

data.items.[0].deliveryAddress.region

最佳答案

为此,我使用此正则表达式来匹配您要丢弃的字符串:

data.items.\[\d+\].classification

假设我有一个 Python 列表,其中包含名为 l 的项目:

l = ["data.items.[0].deliveryAddress.region",
"data.items.[0].classification.scheme",
"data.items.[0].classification.id",
"data.items.[0].description"]

然后,我可以使用 re.match 使用列表理解来仅保留与正则表达式不匹配的值。

>>> import re
>>> [x for x in l if not re.match(r"data.items.\[\d+\].classification", x)]
['data.items.[0].deliveryAddress.region', 'data.items.[0].description']

关于python - 正则表达式匹配键,除了一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066624/

相关文章:

python - 使用 PyCharm 调试器运行 Flask CLI 命令

python - 在 LAMP (CentOS) 服务器上运行 .py 文件 - 从 PHP 开发人员的角度来看

regex - 使用正则表达式重命名命令不起作用

python - 使用Python从以太坊区 block 链中提取信息

python - 在Python中反转字典不会产生结果

Python 正则表达式匹配换行符

PHP Regex - 使用逗号分隔符拆分字符串,忽略标签之间的逗号

regex - 正则表达式量词 : . * 和 .* 有什么区别?

c - C 中的正则表达式 (PCRE)

python - 如何查看 WTForms 验证错误?