我試過如下:正則表達式re.compile,無法得到它的工作
title = 'Die.Simpsons.S02.German'
season = re.compile('.*S\d|\Sd{2}|eason\d|eason\d{2}.*')
test = season.match(title)
print test
,但我總是得到 '沒有'
我試過如下:正則表達式re.compile,無法得到它的工作
title = 'Die.Simpsons.S02.German'
season = re.compile('.*S\d|\Sd{2}|eason\d|eason\d{2}.*')
test = season.match(title)
print test
,但我總是得到 '沒有'
根據您的變量名稱,我假設您對季節編號感興趣,而不是整個標題。如果我是正確的,應該是這樣的:
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.match
你也可以使用reg.search
,那麼你就需要有.*
開頭:
reg = re.compile('(S|Season|eason)(\d+)')
season = reg.search(title).group(2)
// EDIT 托馬斯評論後修復
@ThomasAyoub:謝謝指出,我有一個錯字。固定 – woockashek
謝謝...那完美的作品... – user294015
使用此代碼的工作:
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()))
見demo。
你試圖實現什麼? 請添加預期結果或詳細解釋。 – woockashek
首先'\ Sd {2}'應該是'S \ d {2}',否則你會匹配一個非空白字符和兩個字面ds。請使用在線正則表達式調試器來探索您的表達實際所做的事情。 – jonrsharpe
其實正則表達式適合我。 P3.5。 – baldr