Joa*_*nge 0 .net c# regex string parsing
我有音乐文件名,如:
Gorillaz (2001)
Gorillaz (7th State Mix) (2002)
Gorillaz (2001) (Featuring Travis)
Gorillaz (1Mix) (2003)
Gorillaz (1000) (2001)
Run Code Online (Sandbox Code Playgroud)
如何以最干净,最简单的方式解析年份?
现在我通过查找每个来解析它们'('然后确保()s 之间的字符数是4并且第一个char是1或2并且它们可以被解析,使用TryParse?
我可以使用一个正则表达式解析这些类型的字符串吗?
这一年最长可达50-60岁,因此不超过1950年.
我想这就是你所追求的:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
string[] samples = new[] { "Gorillaz (2001)",
"Gorillaz (7th State Mix) (2002)",
"Gorillaz (2001) (Featuring Travis)",
"Two matches: (2002) (1950)",
"Gorillaz (1Mix) (1952)",
"Gorillaz (1Mix) (2003)",
"Gorillaz (1000) (2001)" };
foreach (string name in samples)
{
ShowMatches(name);
}
}
static readonly Regex YearRegex = new Regex(@"\((19[5-9]\d|200\d)\)");
static void ShowMatches(string name)
{
Console.WriteLine("Matches for: {0}", name);
foreach (Match match in YearRegex.Matches(name))
{
Console.WriteLine(match.Value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将工作到2009年.为了使其超越,请使用@"((19 [5-9]\d | 20 [01]\d))"等.
请注意,仍然打印括号 - 您可以用组构造摆脱它们,但我个人只是使用Substring:)