繁体   English   中英

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

[英]Convert result of matches from regex into list of string

如何将匹配结果列表从正则表达式转换为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

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

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

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

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来获取列表列表。

使用 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();
    }
}

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

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

从历史上看,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);
var regex = new Regex("{([A-Za-z])*}");
var result= regex.Matches(text).Where(p => p.Success).Select(p => p.Value).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM