将匹配结果从正则表达式转换为字符串列表 [英] Convert result of matches from regex into list of string
本文介绍了将匹配结果从正则表达式转换为字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将匹配结果列表从正则表达式转换为 List< string>
?我有此功能,但它始终会生成异常,
How can I convert the list of match result from regex into List<string>
? I have this function but it always generate an exception,
无法转换类型为'System.Text.RegularExpressions.Match'$ b的对象$ b键入 System.Text.RegularExpressions.CaptureCollection。
Unable to cast object of type 'System.Text.RegularExpressions.Match' to type '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.
regex
dog|cat
我希望函数将结果返回到列表<字符串>
I want that the function will return of result into List<string>
dog
cat
推荐答案
有了Regex,您需要使用 Regex。匹配
以获得所需的最终字符串列表:
With the Regex you have, you need to use Regex.Matches
to get the final list of strings like you want:
MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();
这篇关于将匹配结果从正则表达式转换为字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文