【问题标题】:Extract particular group of a repeating substring with regex使用正则表达式提取重复子字符串的特定组
【发布时间】:2015-10-22 11:36:53
【问题描述】:

提供的输入“inputString”可能采用“0/1”、“0/1/2”、...(或任何其他由“/”分隔的至少两位数字的组合)的形式,我写了以下基于正则表达式的提取数字的表达式:

match = re.search("(\d)+/*", inputString)

为了列出最后两位数字,我使用了

match.groups()[-1], match.groups()[-2]

但是,使用“0/1”输入,我只能得到“0”。如何使用正则表达式创建特定的重复子字符串(在我的情况下为数字)。当然,.split('/') 是另一种选择,但我对正则表达式感兴趣。

【问题讨论】:

  • 在你的最后一个例子中 - “0/1”作为输入的期望输出是什么?
  • 您应该将re.search 替换为re.findall,可能。
  • 另外,/* 在您的正则表达式中的用途是什么?
  • @JonClements Desired 是 [0, 1]。
  • @WashingtonGuedes 从输入中可以看出,它不以“/”结尾

标签: python regex


【解决方案1】:

使用$ 将您的搜索定位到行尾。

import re

for text in ('0', '0/1', '0/1/2', 'foo', '0/1/2/3', 'bar'):
    m = re.search(r'(\d)/(\d)$', text)
    if m:
        print(m.groups())
    else:
        print('no match for:', text)

给你:

no match for: 0
('0', '1')
('1', '2')
no match for: foo
('2', '3')
no match for: bar

不过,在一天结束的时候,你很可能会做得更好:

try:
    g1, g2 = text.rsplit('/', 2)
except ValueError:
    pass # do something appropriate

【讨论】:

  • 鉴于我在原始问题下的评论,我认为 m = re.search(r'(\d)/(\d)$', text) 应该有 (\d+) (所以,带“+”)
  • @user3560285 根据需要进行调整 - 关键是将搜索锚定到行尾
【解决方案2】:

您需要使用re.findall 而不是re.search

re.search 只检查字符串中任意位置的单个匹配项。

【讨论】:

  • 我的模式应该从“(\d)+/*”更改为“(\d+)+/*”,因为我对整数感兴趣。我的错。还是谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多