Skip to main content
 首页 » 编程设计

下载电影的 C# 模式匹配

2024年02月05日15wuhuacong

您好,我正在寻找一种模式匹配,它允许我在电影下载后从文件名中获取匹配集合。文件示例是

The.Voices.2014.720p.BDRip.x264.AC3-WiNTeaM.avi 
13.Sins.2014.1080p.BluRay.DTS.x264-HDS.mkv 
A.Million.Ways.to.Die.in.the.West.2014.1080p.WEB-DL.x264.AC3-EVO.mkv 
Ant-Man.2015.1080p.BluRay.x264-SPARKS.mkv 

我希望能够提取没有句点、年份和质量的电影名称。

我认为不能保证这些按此顺序出现,因此理想情况下模式需要灵活。

在此先感谢您的帮助

请您参考如下方法:

extract the name of the movie without periods, the year and the quality.

使用前向否定展望确保年份将成为正则表达式解析的 anchor ,而不一定是电影标题的一部分。

我添加了 John Belushi 题为 1941 的电影作为测试项目。

string data = 
@"1941.1981.1080p.WEB-DL.x264.AC3-EVO.mkv 
The.Voices.2014.720p.BDRip.x264.AC3-WiNTeaM.avi 
13.Sins.2014.1080p.BluRay.DTS.x264-HDS.mkv 
A.Million.Ways.to.Die.in.the.West.2014.1080p.WEB-DL.x264.AC3-EVO.mkv 
Ant-Man.2015.1080p.BluRay.x264-SPARKS.mkv"; 
 
string pattern = @" 
 
^(?<Name>.+?)                  # Movie Name up to year and resolution 
(?!\.[12]\d\d\d\.\d{,3}[ip]\.) # Year and resolution foward negative look ahead as an a pattern anchor 
\.                             # Non captured due to only explicitly capturing. 
(?<Year>\d\d\d\d)              # Capture Year, etc... 
\. 
(?<Resolution>[^.]+) 
\. 
(?<Format>[^.]+)  
 
"; 
 
 
Regex.Matches(data, pattern, RegexOptions.ExplicitCapture          // Only what we ask for (?<> ), ignore non captures 
                           | RegexOptions.Multiline                // ^ makes each line a separate one. 
                           | RegexOptions.IgnorePatternWhitespace) // Allows us to comment pattern only. 
     .OfType<Match>( 
     .Select (mt => new 
                    { 
                        Movie      = Regex.Replace(mt.Groups["Name"].Value, @"\.", " "), 
                        Year       = mt.Groups["Year"].Value, 
                        Resolution = mt.Groups["Resolution"].Value, 
                        Format     = mt.Groups["Format"].Value, 
                    }); 

结果