【问题标题】:python if list_item == re.matchpython if list_item == re.match
【发布时间】:2023-01-31 00:09:19
【问题描述】:

我正在尝试在 python (googlecollab) 中使用条件练习正则表达式模式,但通过从列表 [000 到 999] 中获取正确的数字而陷入(如果...和...) - 我只需要数字,以一个结尾数字“1”(不是 11、111、211 - 我只需要 001、021、031、101),但它在多个条件下不返回任何内容...如果我清除条件中以“和”开头的代码 - 它返回所有, 十一, 一百十一...

list_ = []
list_.append('000')
for a in range(999):
    list_.append(str(a+1))

for i, el in  enumerate(list_):
    if len(el) == 1:
        list_[i] = '00'+el
    elif len(el) == 2:
        list_[i] = '0'+el

for item in list_:
    try:
        if item == re.match(r'\d\d1', item).group() \
        and item != re.match(r'\d11', item).group():
            print(item) 
    except:
        pass    

【问题讨论】:

  • 旁注:您的列表生成代码可以简化为list_ = [str(x).zfill(3) for x in range(1000)]
  • 您可以使用 $ 在字符串末尾查找 1。另外,我不会将您的item 与匹配项进行比较,而是检查匹配项是否为非空。
  • 您可以将前四行(生成list_)简化为list_ = [str(i).zfill(3) for i in range(1000)]

标签: python if-statement design-patterns match python-re


【解决方案1】:

要仅匹配以一个(不是更多)数字 1 结尾的“数字”,请使用以下正则表达式模式:

for i in list_:
    m = re.match(r'd(0|[2-9])1', i)
    if m:
        print(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2017-12-07
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多