【问题标题】:How to use RegEx in C# to take all the matching strings into a collection如何在 C# 中使用 RegEx 将所有匹配的字符串放入一个集合中
【发布时间】:2011-06-16 21:30:05
【问题描述】:

我想将所有匹配项放入一个集合中,或者至少是一个新字符串,其中我的值由空格分隔。

var srcString = @"foo foo %%match1%%, foo %%match2%%, %%match3%% foo foo";

var output = Regex.Match(srcString, @"\%\%(.*)\%\%").Groups[1].Value;

其中输出必须是一个集合,其中“match1”作为元素,“match2”作为下一个元素,依此类推,或者至少类似于“match1 match2 match3”。

谢谢!

【问题讨论】:

    标签: c# regex string c#-4.0 collections


    【解决方案1】:

    这应该可以解决问题

    var srcString = @"foo foo %%match1%%, foo %%match2%%, %%match3%% foo foo";
    
    IEnumberable<string> results = Regex.Matches(srcString, @"\%\%(.*?)\%\%").Cast<Match>().Select(match => match.Value);
    

    【讨论】:

    • 谢谢!你很有帮助
    【解决方案2】:

    试试这个:

      var srcString = @"foo foo %%match1%%, foo %%match2%%, %%match3%% foo foo";
                var match = Regex.Match(srcString, @"%%([^%]+)%%");
                while (match.Success)
                {
                    Console.WriteLine(match.Groups[1].Value);
                    match = match.NextMatch();
                }
    

    输出:

    match1
    match2
    match3
    

    【讨论】:

    • 谢谢!你很有帮助!
    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 2013-12-07
    • 2018-07-24
    • 2011-09-13
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多