Convert result of matches from regex into list of string

后端 未结 6 880
余生分开走
余生分开走 2020-12-14 15:22

How can I convert the list of match result from regex into List? I have this function but it always generate an exception,

6条回答
  •  -上瘾入骨i
    2020-12-14 15:48

    Historically the Regex collections have not implemented the generic collection interfaces, and the LINQ extension methods you're using operate on the generic interfaces. MatchCollection was updated in .NET Core to implement IList, and thus can be used with the Selectextension method, but when you move to .NET Standard 2.0, that interface implementation isn't there, and thus you can't just callSelect. Instead, you'll need to use the LINQ Cast or OfType extensions to convert to an IEnumerable, and then you can use Select on that. Hope that helps.

    Example

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

提交回复
热议问题