【问题标题】:Python regex bool test over a list of stringsPython regex bool 测试字符串列表
【发布时间】:2018-06-25 15:35:06
【问题描述】:

我想检查列表中的某些参数是否与某个模式匹配(两个大写字母后跟一个整数:XX999999)。我使用工作正常的(python)正则表达式。但是,如果我遍历一个列表,则无法正确识别该模式。

可能测试失败是因为我将列表参数显式调用为字符串str(string)?但是,如果我没有将列表参数显式调用为字符串,则会收到错误消息(TypeError: expected string or bytes-like object)。

有什么想法吗?谢谢!

import re

# Is true
print(bool(re.match("^([A-Z]+[0-9]+)+$", "XZ291053")))

# Is false
print(bool(re.match("^([A-Z]+[0-9]+)+$", "ye291053")))

# Does not work
string = ['XZ291053','ye291053','AU291049','GI291053']
for s in string:
    print(bool(re.match("^([A-Z]+[0-9]+)+$", str(string))))

【问题讨论】:

  • [re.match(r"^([A-Z]+[0-9]+)+$", i) for i in string]
  • print(bool(re.match("^([A-Z]+[0-9]+)+$", s))) ?
  • string 是一个列表。您需要将正则表达式应用于列表中的当前字符串s
  • 谢谢 Wiktor,现在我明白了……我想我该收工了 :-)
  • 你不应该命名变量string,它会覆盖一个Python内置模块

标签: python regex string loops


【解决方案1】:

您可以使用列表推导来执行此操作,将正则表达式应用于列表中的每个字符串:

[re.match(r"^([A-Z]+[0-9]+)+$", i) for i in string]

为了与您的原始帖子保持一致:

[bool(re.match(r"^([A-Z]+[0-9]+)+$", i)) for i in string]

这给出了:

[True, False, True, True]

此外,对您的正则表达式稍作修改以匹配您对所需模式的描述:

^[A-Z]{2}[0-9]+

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多