2016-08-14 64 views
1

爲什麼這個正則表達式不正確地解析字符串「Season 02 Episode 01」?解析正則表達式問題季節/情節模式

例如,這是不匹配:

var fileName = "Its Always Sunny in Philadelphia Season 02 Episode 01 - Charlie Gets Crippled.avi" 

// Regex explanation: 
// Starts with "S" and can contain more letters, can continue with space, then contains two numbers. 
// Then starts with "E" again and can contain more letters, can continue with space, then contains two numbers. 
var pattern = @"S\w?\s?(\d\d)\s?E\w?\s?(\d\d)"; 
var regex = new Regex(pattern, RegexOptions.IgnoreCase); 
var match = regex.Match(fileName); 

回答

1

使用*代替?

?爲0或1的時間。 *爲0或更多次。

+0

你是完全正確的,那是我的錯誤。這是固定模式:'var pattern = @「S \ w * \ s *(\ d \ d)\ s * E \ w * \ s *(\ d \ d)」;'。 –

1

開始以 「S」,並且可以包含多個字母[...]

你的意思是+,不?

var pattern = @"S\w+\s+(\d+)\s+E\w+\s+(\d+)"; 

請注意,這個正則表達式非常不確定。注意誤報。我建議讓表達更具體。

+0

+1('d +)',這是我的正則表達式的改進。但在其他情況下,'+'不起作用('*'的確如M.kazem Akhgary所提出的那樣),因爲我期望有0個或更多的實例。原帖中未指定的內容(我對此感到抱歉,我認爲這是理所當然的,我不應該這麼做)是'S02E01'也是一場比賽。關於「小心誤報」你也是對的,但是輸入格式差別很大,所以這種模式是有目的的。 –

+0

是的,你說得對,要抓住'S01'就得用這顆星。相當常見的寫作方式,應該考慮到這一點。 – Tomalak