[英]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
我為 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.