正则匹配结果转字符串列表如何将正则匹配结果列表转列表?我有这个功能,但它总是产生异常,无法将类型为“System.Text.RegularExpressions.Match”的对象转换为“System.Text.RegularExpressions.CaptureCollection”。publicstaticListExtractMatch(stringcontent,stringpattern){List_returnValue=newList();匹配_matchList=Regex.Match(内容,模式);while(_matchList.Success){foreach(Group_groupin_matchList.Groups){foreach(CaptureCollection_capturesin_group.Captures)//error{foreach(Capture_capin_captures){_returnValue.Add(_cap.ToString());}}}}返回_returnValue;如果我有这个字符串,我就有了一只狗和一只猫。Regexdog|cat我希望函数将结果返回给Listdogcat使用Regex,您需要使用Regex.Matches来获取所需字符串的最终列表:MatchCollectionmatchList=Regex.Matches(Content,Pattern);varlist=matchList.Cast().Select(match=>match.Value).ToList();通过正则表达式匹配交叉发布答案——要获得正则表达式匹配列表,您可以:varlookfor=@"something(with)multiple(pattern)(groups)";varfound=Regex.Matches(来源,查找,正则表达式选项);varcaptured=found//linq-ifyintolist.Cast()//扁平化为单个列表.SelectMany(o=>//linq-ifyo.Groups.Cast()//不需要pattern.Skip(1)//选择你想要的.Select(c=>c.Value));这会将所有捕获的值“扁平化”到单个列表中。要维护捕获组,请使用Select而不是SelectMany来获取列表的列表。使用Linq的可能解决方案:使用System.Linq;使用System.Text.RegularExpressions;staticclassProgram{staticvoidMain(string[]aargs){stringvalue="我有一只狗和一只猫。";正则表达式regex=newRegex("狗|猫");varmatchesList=(fromMatchminregex.Matches(value)selectm.Value).ToList();这是您的代码的另一个解决方案。以上就是C#学习教程的全部内容:将正则表达式的匹配结果转换为字符串列表。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——while(_matchList.Success){_returnValue.Add(_matchList.Value);_matchList=_matchList.NextMatch();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
