如何在C#中使用RegEx将所有匹配的字符串放入集合中

本文关键字:字符串 集合 RegEx | 更新日期: 2023-09-27 17:59:25

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

var srcString = @"foo foo %%match1%%, foo %%match2%%, %%match3%% foo foo";
var output = Regex.Match(srcString, @"'%'%(.*)'%'%").Groups[1].Value;

其中output必须是一个集合,其中"match1"为元素,"match2"为下一个元素,依此类推,或者至少类似于"match1-match2-match3"。

谢谢!

如何在C#中使用RegEx将所有匹配的字符串放入集合中

这应该可以完成

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

试试这个:

  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