python中如何通过正则表达式获取部分字符串

2024-04-28 20:28:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过正则表达式得到字符串的一部分,我尝试了这个方法,但它返回的结果比我需要的要多。这是我的代码:

Release_name = 'My Kitchen Rules S10E35 720p HDTV x264-ORENJI'
def get_rls(t):
    w = re.match(".*\d ", t)

    if not w: raise Exception("Error For Regular Expression")
    return w.group(0)


regular_case = [Release_name]
for w in regular_case:
    Regular_part = get_rls(w)
    print(">>>> Regular Part: ", Regular_part)

此示例的代码“My Kitchen Rules S10E35 720p HDTV x264-ORENJI” 返回这个“My Kitchen Rules S10E35”,但我不需要“S10E35”,只需返回这个My Kitchen Rules


Tags: 代码namegetreleasemyrulescasex264
1条回答
网友
1楼 · 发布于 2024-04-28 20:28:54

你可以用

w = re.match(r"(.*?)\s+S\d+E\d+", t)

由于您需要的值在组1中:

^{pr2}$

请参见Python demo,输出是>>>> Regular Part: My Kitchen Rules。在

细节

  • (.*?)-除换行符外的任何0+字符,尽可能少
  • \s+-1+个空格
  • S\d+E\d+-S字符,1+位数,E和1+位数

re.match将只从字符串的开头开始匹配,^不需要在模式的开头。在

相关问题 更多 >