簡體   English   中英

用於匹配季節和劇集的正則表達式

[英]Regex for matching season and episode

我正在為自己制作小應用程序,我想找到與模式匹配的字符串,但找不到正確的正則表達式。

Stargate.SG-1.S01E08.iNT.DVDRip.XviD-LOCK.avi

那是我擁有的字符串示例,我只想知道它是否包含 S[NUMBER]E[NUMBER] 的子字符串,每個數字最長 2 位。

你能給我一個線索嗎?

正則表達式

是使用命名組的正則表達式:

S(?<season>\d{1,2})E(?<episode>\d{1,2})

用法

然后,您可以像這樣獲得命名組(季節和劇集):

string sample = "Stargate.SG-1.S01E08.iNT.DVDRip.XviD-LOCK.avi";
Regex  regex  = new Regex(@"S(?<season>\d{1,2})E(?<episode>\d{1,2})");

Match match = regex.Match(sample);
if (match.Success)
{
    string season  = match.Groups["season"].Value;
    string episode = match.Groups["episode"].Value;
    Console.WriteLine("Season: " + season + ", Episode: " + episode);
}
else
{
    Console.WriteLine("No match!");
}

正則表達式的解釋

S                // match 'S'
(                // start of a capture group
    ?<season>    // name of the capture group: season
    \d{1,2}      // match 1 to 2 digits
)                // end of the capture group
E                // match 'E'
(                // start of a capture group
    ?<episode>   // name of the capture group: episode
    \d{1,2}      // match 1 to 2 digits
)                // end of the capture group

這里有一個很棒的在線測試站點: http : //gskinner.com/RegExr/

使用它,這是您想要的正則表達式:

S\d\dE\d\d

不過,除此之外,您還可以做很多花哨的技巧!

看看一些媒體軟件,比如 XBMC,它們都有非常強大的電視節目正則表達式過濾器

這里這里

我為 S[NUMBER1]E[NUMBER2] 設置的正則表達式是

S(\d\d?)E(\d\d?)       // (\d\d?) means one or two digit

您可以通過<matchresult>.group(1) NUMBER1,通過<matchresult>.group(2)

我想提出一個更復雜的正則表達式。 我沒有“。:- _”,因為我用空格替換它們

str_replace(
        array('.', ':', '-', '_', '(', ')'), ' ',

這是將標題拆分為標題季節和劇集的捕獲正則表達式

(.*)\s(?:s?|se)(\d+)\s?(?:e|x|ep)\s?(\d+)

例如達芬奇的惡魔 se02ep04 和變體https://regex101.com/r/UKWzLr/3

我無法涵蓋的唯一情況是季節和數字之間有間隔,因為如果標題對我不起作用,字母 s 或 se 將成為一部分。 無論如何,我還沒有看到這樣的案例,但這仍然是一個問題。

編輯:我設法用第二行繞過它

    $title = $matches[1];
    $title = preg_replace('/(\ss|\sse)$/i', '', $title);

這樣,如果名稱是系列的一部分,我將刪除 's' 和 'se' 的結尾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM