将匹配结果从正则表达式转换为字符串列表

时间:2012-10-04 15:05:06

标签: c# .net regex

如何将匹配结果列表从正则表达式转换为List<string>?我有这个功能,但它总是会产生异常,

  

无法转换'System.Text.RegularExpressions.Match'类型的对象   输入'System.Text.RegularExpressions.CaptureCollection'。

public static List<string> ExtractMatch(string content, string pattern)
{
    List<string> _returnValue = new List<string>();
    Match _matchList = Regex.Match(content, pattern);
    while (_matchList.Success)
    {
        foreach (Group _group in _matchList.Groups)
        {
            foreach (CaptureCollection _captures in _group.Captures) // error
            {
                foreach (Capture _cap in _captures)
                {
                    _returnValue.Add(_cap.ToString());
                }
            }
        }
    }
    return _returnValue;
}

如果我有这个字符串,

I have a dog and a cat.

正则表达式

dog|cat

我希望函数将结果返回List<string>

dog
cat

6 个答案:

答案 0 :(得分:92)

使用正则表达式,您需要使用Regex.Matches来获取您想要的最终字符串列表:

MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();

答案 1 :(得分:12)

Looping through Regex Matches -

交叉发布答案

要获得正则表达式匹配列表,您可以:

var lookfor = @"something (with) multiple (pattern) (groups)";
var found = Regex.Matches(source, lookfor, regexoptions);
var captured = found
                // linq-ify into list
                .Cast<Match>()
                // flatten to single list
                .SelectMany(o =>
                    // linq-ify
                    o.Groups.Cast<Capture>()
                        // don't need the pattern
                        .Skip(1)
                        // select what you wanted
                        .Select(c => c.Value));

这会将所有捕获的值“展平”到一个列表。要维护捕获组,请使用Select而不是SelectMany来获取列表列表。

答案 2 :(得分:5)

使用Linq的可能解决方案:

using System.Linq;
using System.Text.RegularExpressions;

static class Program {
    static void Main(string[] aargs) {
        string value = "I have a dog and a cat.";
        Regex regex = new Regex("dog|cat");
        var matchesList = (from Match m in regex.Matches(value) select m.Value).ToList();
    }
}

答案 3 :(得分:1)

这是另一种适合您代码的解决方案。

while (_matchList.Success)
{
    _returnValue.Add(_matchList.Value);
    _matchList = _matchList.NextMatch();
}

答案 4 :(得分:0)

从历史上看,Regex集合没有实现通用集合接口,并且您使用的LINQ扩展方法在通用接口上运行。 MatchCollection在.NET Core中进行了更新,以实现IList,因此可以与Selectextension方法一起使用,但是当您移至.NET Standard 2.0时,该接口实现不存在,因此您不能只调用Select。相反,您需要使用LINQ CastOfType扩展名来转换为IEnumerable,然后可以在其上使用Select。希望有帮助。

示例

Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).Cast<Match>().Select(c => c.Value);

Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).OfType<Match>().Select(c => c.Value);

答案 5 :(得分:-1)

var regex = new Regex("{([A-Za-z])*}");
var result= regex.Matches(text).Where(p => p.Success).Select(p => p.Value).ToList();