【问题标题】:C# Store Regex results in array [duplicate]C#将正则表达式结果存储在数组中[重复]
【发布时间】:2014-05-21 21:25:43
【问题描述】:

是否可以在 C# 中将 Regex 结果存储在 Array 中,因此每个成员将存储每个 Regex 匹配项

就像在 Python 中一样:

text="A text is"
a=re.findall("[A-Z/a-z]+",text)
print(a[:]) //If write print(a[0]) it will return 'A', a[1] will give 'text', a[2] 'is', a[:] prints whole results

那么是否可以将正则表达式结果存储在 C# 中,因此数组的每个成员都将由每个匹配项组成 谢谢!

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    您可以使用Regex.Matches 方法。这将返回一个包含所有匹配项的MatchCollection。匹配的文本是该集合的每个项目 (Match) 的 Value 属性。

    因此,使用与您的示例等效的:

    var text = "A text is";
    var matches = Regex.Matches(text, "[A-Za-z]+);
    
    matches[0].Value.Dump();
    
    【解决方案2】:

    是的。只是用括号括起来的值。然后访问组数组。

    Match match = Regex.Match("abc","(a)(b)(c)");
    string a = match.Groups[1].Value;
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2019-10-20
      相关资源
      最近更新 更多