2012-03-30 48 views
0

我想用另一個正則表達式模式替換一個正則表達式模式。正則表達式:用另一個替換一個模式

st_srt = 'Awake.01x02.iNTERNAL.WEBRiP.XViD-GeT.srt' 
st_mkv = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.mkv' 

pattern = re.compile('\d+x\d+') # for st_srt 
re.sub(pattern, 'S\1E\2',st_srt) 

我知道使用S\1E\2這裏是錯誤的。我使用\1 and \2的原因是爲了獲得值01 and 02並在S\1E\2中使用它。

我所需的輸出是:

st_srt = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.srt' 

那麼,什麼是實現這一目標的正確方法。

+1

你不能用另一個替換正則表達式正則表達式,你正在使用正則表達式來替換另一個字符串的字符串。非常重要的區別。相信我,使用正則表達式來處理* other * regexes是你不需要的噩夢。 – 2012-03-30 21:22:44

+0

@JustinMorgan:感謝您的輸入,但比用正則表達式替換另一個正則表達式還是使用基於正則表達式的解決方案來實現我所需的輸出更爲正確。 – RanRag 2012-03-30 21:24:50

+0

我認爲你的意思是你想在你的搜索字符串中捕獲一個組,並在替換字符串中使用該組。 – alan 2012-03-30 21:26:43

回答

2

你需要捕捉你想要保存的內容。試試這個:使用此正則表達式

pattern = re.compile(r'(\d+)x(\d+)') # for st_srt 
st_srt = re.sub(pattern, r'S\1E\2', st_srt) 
+0

(1)你應該使用原始字符串。 (2)如果你不打算用它的返回值做任何事情,你不應該調用're.sub'。 ;-) – ruakh 2012-03-30 21:29:01

+0

現在我們得到了'Awake.S \ x01E \ x02.iNTERNAL.WEBRiP.XViD-GeT.srt'。 – RanRag 2012-03-30 21:29:53

+0

@ruakh - 謝謝,我在假定它正確的情況下剪切並粘貼了他的python代碼。我是一個正規人,而不是一個蟒蛇人。你能幫助語法嗎? – 2012-03-30 21:32:15

1

嘗試:

([\w+\.]+){5}\-\w+ 

的stirngs複製到這裏:http://www.gskinner.com/RegExr/

並粘貼正則表達式在頂部。

它捕獲每個字符串的名稱,忽略擴展名。

然後,您可以繼續並將所需的擴展名附加到所需的字符串。

編輯:

這就是我用來做你以後:

import re 
st_srt = 'Awake.01x02.iNTERNAL.WEBRiP.XViD-GeT.srt' // dont actually need this one 
st_mkv = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.mkv' 
replace_pattern = re.compile(r'([\w+\.]+){5}\-\w+') 
m = replace_pattern.match(st_mkv) 

new_string = m.group(0) 
new_string += '.srt' 

>>> new_string 
'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.srt' 
+0

我認爲OP需要多一點解釋。 – RanRag 2012-03-30 21:55:33

+0

您可能希望將'm = replace_pattern.match(st_mkv)'更改爲'm = replace_pattern.match(st_srt)'。 – RanRag 2012-03-30 22:11:27

+0

@AlexW:老兄,如果你要將我的答案複製並粘貼到你的答案中,你應該至少改變所有的變量名稱:) – alan 2012-03-30 22:12:41

2

嗯,看起來你已經接受了答案,但我想這是你說你」再試圖做的,這是擺脫「st_mkv」替換字符串,然後在「st_srt」使用它:

import re 
st_srt = 'Awake.01x02.iNTERNAL.WEBRiP.XViD-GeT.srt' 
st_mkv = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.mkv' 

replace_pattern = re.compile(r'Awake\.([^.]+)\.') 
m = replace_pattern.match(st_mkv) 
replace_string = m.group(1) 

new_srt = re.sub(r'^Awake\.[^.]+\.', 'Awake.{0}.'.format(replace_string), st_srt) 
print new_srt 
+0

+1謝謝你另一個很好的答案。 – RanRag 2012-03-30 21:52:51

0
import re 

st_srt = 'Awake.01x02.iNTERNAL.WEBRiP.XViD-GeT.srt' 

st_mkv = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.mkv' 

pattern = re.compile(r'(\d+)x(\d+)') 

st_srt_new = re.sub(pattern, r'S\1E\2', st_srt) 

print st_srt_new 
相關問題