如何将匹配结果列表从正则表达式转换为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;
}
Run Code Online (Sandbox Code Playgroud)
如果我有这个字符串,
I have a dog and a cat.
Run Code Online (Sandbox Code Playgroud)
正则表达式
dog|cat
Run Code Online (Sandbox Code Playgroud)
我希望函数将结果返回到 List<string>
dog
cat
Run Code Online (Sandbox Code Playgroud)
man*_*lds 101
使用正则表达式,您需要使用Regex.Matches
以获得您想要的最终字符串列表:
MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();
Run Code Online (Sandbox Code Playgroud)
drz*_*aus 12
通过正则表达式匹配交叉发布回答-
要获得正则表达式匹配列表,您可以:
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));
Run Code Online (Sandbox Code Playgroud)
这会将所有捕获的值"展平"到单个列表.要维护捕获组,请使用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();
}
}
Run Code Online (Sandbox Code Playgroud)