【问题标题】:Use regex to match indicators (a) (b) and so on使用正则表达式匹配指标 (a) (b) 等等
【发布时间】:2019-01-24 15:41:55
【问题描述】:

我有一个演讲列表,我想删除所有在 (a)..(z)、(A)..(Z) 和 (i)...(九)。我找不到正确的正则表达式匹配来包含所有这些可能性。我试过没有成功:

list = [item for item in list if '(\w)' in item]

我应该一个一个地做,还是有更有效的方法? 谢谢!

【问题讨论】:

  • 您必须使用re 模块。 "(\w)" in itemitem 中查找文字字符串 "(\w)"
  • 请提供示例输入和预期响应
  • 我的列表如下list=['this is the first (a) sentence', 'this is the second (b) sentence', 'this is the third sentence']我想剔除所有包含(a)和(b)等表达式的列表元素,以便恢复list=['this is the third sentence']

标签: python regex list


【解决方案1】:

您可以这样做:

import re

rx = re.compile(r"^(\(\w\)|\([ivx]+\)).*", re.MULTILINE)

list = [item for item in list if not rx.match(item)]

请参阅re library documentation 了解更多信息。

【讨论】:

  • 正则表达式中不需要.*。你不是想匹配整个字符串,只是开始。
【解决方案2】:

首先,要进行正则表达式匹配,您需要re 模块(或regex)。您还需要注意正则表达式中的特殊标记,在本例中是括号。

这是一个有效的示例正则表达式:

re.search(r"\(([A-Za-z]|v?i{1,3}|i[vx])\)", item)

上述正则表达式将涵盖 (A) 到 (Z)、(a) 到 (z),以及 (i)、(ii)、... (viii)、(ix)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-19
    • 2015-02-20
    • 1970-01-01
    • 2021-06-15
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    相关资源
    最近更新 更多