首页 > 解决方案 > 如何在 C# 中使用正则表达式从字符串中提取多个子字符串

问题描述

我从网上搜索,我只有部分解决方案,所以我提出了这个问题。

输入:

[A] this is A, and , [B] this is B, and hello , [C] this is C - From Here

我想要一个清单:

list[0] == "this is A, and"
list[1] == "this is B, and hello"
list[2] == "this is C"
list[3] == "From Here"

我发现我应该有这样的东西:

Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");
List<string> matches = pattern.Matches(input).OfType<Mathc>().Select(m => m.value).Distinct().ToList();

但它不起作用。我想问如何使它工作。谢谢。

标签: c#regex

解决方案


正则表达式是正确的,您唯一需要做的就是迭代匹配组。在您的情况下,第一组将是整个句子,因此,您可以简单地跳过第一项。
PS,当然不要忘记检查是否存在至少一个匹配结果。此外,如果此函数将多次执行,我建议您将正则表达式提取到类的静态成员中(因为性能和内存使用情况)。

private static readonly Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");

该方法的最终版本(将模式作为静态成员)如下所示。

public static List<string> GetMatches(string input)
{
    var matchResult = pattern.Match(input);
    if (matchResult.Length > 0)
    {
        return matchResult.Groups.Values
            .Skip(1)
            .Select(x => x.Value)
            .ToList();
    }
    
    return new List<string>();
}

推荐阅读