【问题标题】:multi regex to grab numbers in python多正则表达式在python中获取数字
【发布时间】:2021-12-17 05:57:18
【问题描述】:

我不是正则表达式专家,但我是从头开始做的 基于此,我只需要获取数字和字母 [a-e]:

SnnEnn   where n represent numbers  
SnnEnnl  where l = letter [a-e]  

nnXnn    where n represent numbers 
nnXnnl   where l = letter [a-e] 

但在少数情况下它会失败:

02x01      match '02x01'                                      fail (It should be '02' '01')
03x02a     match '03x02'..............groups 'a'             fail (It should be '03' '02' 'a')
S03E01     match 'S03E01'.............groups '03'  '01'      ok
S03E01a    match 'S03E01a'............groups 'S03E01'  'a'   fail.(It should be '03' '01' 'a')

03x02xxxx  match '03X02xxxx' groups '03x02xxxx'    fail (it should be just [a-e] and limit to one letter) 
S03E01xxx  match '03E01xxxx' groups '03e01xxxx'    fail (idem)

regex101

我正在使用这个正则表达式:

(\d+[x]\d+\w)([a-e])|(\d+[x]\w+)|\bS(?P<Season>\d+)E(?P<Episode>\d+)|(\b[s]\d+[e]\d+)([a-e])

感谢您的帮助

【问题讨论】:

  • 嗨,这是一个例子。这意味着它只需要一次抓取“a-e”(我只需要从 a 到 e 的一个字母)
  • 几乎对于第二个正则表达式 (5zdiDU/1) ,它不应该像这样抓取字符串:S03x01e 因为 'x' ,它应该始终是 SnnEnn 或 nnXnn

标签: python regex show


【解决方案1】:

你可能会使用

\b(S)?(?P<Season>\d+)(?(1)E|x)(?P<Episode>\d+)(?P<Letter>[a-e]?)\b
  • \b一个字边界
  • (S)? 可以选择在组 1 中捕获 S
  • (?P&lt;Season&gt;\d+)Season - 匹配 1+ 位
  • (? 有条件的(请参阅 this page about conditionals
    • (1)E 如果组 1 存在,匹配 E
    • |否则
    • x匹配x
  • )关闭条件
  • (?P&lt;Episode&gt;\d+)Episode - 匹配 1+ 位
  • (?P&lt;Letter&gt;[a-e]?)Letter - 匹配范围 a-e
  • \b一个字边界

Regex demo

【讨论】:

  • 几乎,它不应该匹配这样的字符串:S03x01e 因为 'x' ,它应该总是 SnnEnn 或 nnXnn,其中 nn 代表数字
  • @JohnW 您可以使用条件 \b(S)?(\d+)(?(1)E|x)(\d+)([a-e]?)\b 并且值在第 2、3 和 4 组中,请参阅 regex101.com/r/QzpzLp/1
  • 是的第四只鸟,它起作用了。只是一个问题:'(?(1)E | x)'这是否意味着,如果第一个字符是'S'然后匹配'E'否则'x'?谢谢
  • @JohnW 没错,更多信息请参见this page
猜你喜欢
  • 2019-09-07
  • 2016-09-14
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
相关资源
最近更新 更多