Python regex重新编译,无法使其工作

Python regex重新编译,无法使其工作,python,regex,Python,Regex,我尝试了以下方法: title = 'Die.Simpsons.S02.German' season = re.compile('.*S\d|\Sd{2}|eason\d|eason\d{2}.*') test = season.match(title) print test 但我总是收到“无”使用以下代码: import re regex = r".*S(eason)?\d{1,2}.*" test_str = "Die.Simpsons.S02.German" matches = re.

我尝试了以下方法:

title = 'Die.Simpsons.S02.German'
season = re.compile('.*S\d|\Sd{2}|eason\d|eason\d{2}.*')
test = season.match(title)
print test
但我总是收到“无”

使用以下代码:

import re

regex = r".*S(eason)?\d{1,2}.*"
test_str = "Die.Simpsons.S02.German"
matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found : {match}".format(matchNum = matchNum, match = match.group()))

请参阅。

根据您的变量名,我假设您对季号感兴趣,而不是对整个标题感兴趣。如果我是对的,它应该是这样的:

title = 'Die.Simpsons.S02.German'

# This will match Die.Simpsons.S1, Die.Simpsons.S01, Die.Simpsons.Season1 etc ...
reg = re.compile('.*(S|Season|eason)(\d+)')

# get only the season number, group(0) gives full match, group(1) first '()' and so on
season = reg.match(title).group(2)

print season # prints '2'
您也可以使用reg.search来代替reg.match,这样您就不需要使用。*开始时:

reg = re.compile('(S|Season|eason)(\d+)')
season = reg.search(title).group(2)
//编辑
修正了Thomas comment后的问题

您试图实现的目标是什么?请添加预期结果或详细解释。首先,\Sd{2}应该是S\d{2},否则您将匹配一个非空白字符和两个文本ds。请使用在线正则表达式调试器来探索表达式的实际功能。实际上正则表达式对我有用。P3.5.这个应该可以工作,并且在重新编译时可读性更好。'*S | Season | eason\d{1,2}.*'我只是认为OP不知道如何打印匹配值:if test:print test.group