首页 > 解决方案 > 多正则表达式在python中获取数字

问题描述

我不是正则表达式的专家,但我是从头开始做的,我需要根据这个抓取数字和字母 [ae]:

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)

正则表达式101

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

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

感谢您的帮助

标签: pythonregexshow

解决方案


你可能会使用

\b(S)?(?P<Season>\d+)(?(1)E|x)(?P<Episode>\d+)(?P<Letter>[a-e]?)\b
  • \b一个词的边界
  • (S)?可选择S在第 1 组中捕获
  • (?P<Season>\d+)Season- 匹配 1+ 位
  • (?有条件的(有关条件的请参阅此页面
    • (1)E如果组 1 存在,匹配E
    • |别的
    • x匹配x
  • )关闭条件
  • (?P<Episode>\d+)Episode- 匹配 1+ 位
  • (?P<Letter>[a-e]?)Letter- 匹配范围 ae
  • \b一个词的边界

正则表达式演示


推荐阅读