【问题标题】:Extract numbers if string format matches如果字符串格式匹配,则提取数字
【发布时间】:2018-08-25 17:28:54
【问题描述】:

我想检查输入字符串是否遵循某种模式,以及它是否确实从中提取信息。

我的模式是这样的Episode 000 (Season 00)。 00 是范围从 0 到 9 的数字。现在我想检查这个输入Episode 094 (Season 02)是否匹配这个模式,因为它应该提取这两个数字,所以我最终得到两个整数变量942

string latestFile = "Episode 094 (Season 02)";
if (!Regex.IsMatch(latestFile, @"^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$"))
    return

int Episode = Int32.Parse(Regex.Match(latestFile, @"\d+").Value);
int Season = Int32.Parse(Regex.Match(latestFile, @"\d+").Value);

我检查整个字符串是否与模式匹配的第一部分有效,但我认为它可以改进。对于第二部分,我实际上提取了我被卡住的数字,而我在上面发布的内容显然不起作用,因为它从字符串中获取所有数字。因此,如果你们中的任何人能帮我弄清楚如何只提取Episode 之后的三个数字字符和Season 之后的两个字符,那就太好了。

【问题讨论】:

  • 如果我告诉你有带有more than 10,000 episodes? 的节目会怎样 在该列表中还有一个节目超过 100 季(TV Slagalica,一个塞尔维亚游戏节目,截至发帖时有 104 季)

标签: c# regex


【解决方案1】:

在您的正则表达式 ^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$ 中,您正在捕获组中捕获 EpisodeSeason,但您真正想要捕获的是数字。您可以像这样切换捕获组:

^Episode\s([0-9][0-9][0-9])\s\(Season\s([0-9][0-9])\)$

这样匹配3位数字[0-9][0-9][0-9]可以写成\d{3}[0-9][0-9]写成\d{2}

看起来像 ^Episode\s(\d{3})\s\(Season\s(\d{2})\)$

要匹配一个或多个数字,您可以使用\d+

\swhitespace character 匹配。您可以使用\s 或空格。

您的正则表达式可能如下所示:

^Episode (\d{3}) \(Season (\d{2})\)$

string latestFile = "Episode 094 (Season 02)";
GroupCollection groups = Regex.Match(latestFile, @"^Episode (\d{3}) \(Season (\d{2})\)$").Groups;
int Episode = Int32.Parse(groups[1].Value);
int Season = Int32.Parse(groups[2].Value);
Console.WriteLine(Episode);
Console.WriteLine(Season);

这将导致:

94
2

Demo C#

【讨论】:

  • 如果您想确保剧集始终为 3 位数字,季节为 2 位数字,您可以将其更改为 ^Episode (\d{3}) \(Season (\d{2})\)$
  • @msokrates 没错。我已经更新了我的答案。
【解决方案2】:
^Episode (\d{1,3}) \(Season (\d{1,2})\)$

捕获 2 个数字(即使长度为 1 到 3/2)并将它们作为一个组返回。 您可以更进一步并为您的群组命名:

^Episode (?<episode>\d{1,3}) \(Season (?<season>\d{1,2})\)$

然后打电话给他们。

使用组的示例:

string pattern = @"abc(?<firstGroup>\d{1,3})abc";
string input = "abc234abc";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(input);
string result = match.Groups["firstGroup"].Value; //=> 234

您可以查看表达式的含义并对其进行测试here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2015-10-29
    相关资源
    最近更新 更多