2016-11-16 3 views
-1

は、私は、次の試した仕事を得ることはできません。正規表現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 

が、私はいつもこのコードを使用して 'どれも'

+1

達成しようとしていることはありますか? 予期した結果を追加したり、詳細を説明してください。 – woockashek

+2

'\ Sd {2}'は 'S \ d {2}'でなければなりません。そうでなければ、空白以外の文字と2つのリテラルdsをマッチさせます。実際の表現が何であるかを調べるには、オンラインの正規表現デバッガを使用してください。 – jonrsharpe

+0

実際は正規表現が私のために働いています。 P3.5。 – baldr

答えて

3

変数名に基づいてタイトル全体ではなく、シーズン番号に興味があると思います。私が正しい場合は、次のようになります。その代わりreg.match

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 = re.compile('(S|Season|eason)(\d+)') 
season = reg.search(title).group(2) 

// EDIT トーマスコメント後に修正されました

+1

@ThomasAyoub:指摘してくれてありがとう、私は誤字がありました。 – woockashek

+0

固定されています...完璧に動作します... – user294015

0

を受けていないことは動作します:

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