C# 获取正则表达式匹配项的列表
我有一个名为line的字符串,我想用regex解析它:C# 获取正则表达式匹配项的列表,c#,regex,C#,Regex,我有一个名为line的字符串,我想用regex解析它: Regex pattern = new Regex(@"^(line|LINE) (?<lineNr>\d+): (word|WORD) (?<Key_1>\w+) ( (?<e>(e1|e2)) (?<Key_2>\w+))* (?<s>\w+)$"); if (pattern.IsMatch(line)) { Match match = pattern.Match(li
Regex pattern = new Regex(@"^(line|LINE) (?<lineNr>\d+): (word|WORD) (?<Key_1>\w+) ( (?<e>(e1|e2)) (?<Key_2>\w+))* (?<s>\w+)$");
if (pattern.IsMatch(line))
{
Match match = pattern.Match(line);
int lineNr = Int32.Parse(match.Groups["lineNr"].Value);
string Key_1 = match.Groups["Key_1"].Value;
string e = match.Groups["e"].Value;
string Key_2 = match.Groups["Key_2"].Value;
string s = match.Groups["s"].Value;
}
我不知道e和Key_2的重复计数,我想将它们全部添加到数组中。
有可能抓住所有的人吗
//编辑
Regex pattern = new Regex(@"^(line|LINE) (?<lineNr>\d+): (word|WORD) (?<Key_1>\w+) ( (?<e>(e1|e2)) (?<Key_2>\w+))* (?<s>\w+)$");
Match match = pattern.Match(line);
if(match.Success)
{
Regex p = new Regex(@" (?<e>(e1|e2)) (?<Key_2>\w+))");
MatchCollection matches = p.Matches(line);
foreach (Match m in matches)
{
string Key_2 = m.Groups["Key_2"].Value;
string e = m.Groups["e"].Value;
//add matches to array
}
int lineNr = Int32.Parse(match.Groups["lineNr"].Value);
string Key_1 = match.Groups["Key_1"].Value;
string s = match.Groups["s"].Value;
}
这可能会奏效:
var newArray = pattern.Matches( line ).OfType<Match>.Select( m => new { e = m.Groups["e"].Value, Key_2 = m.Groups["Key_2"].Value } ).ToArray();
目前,您不必要地对字符串进行了两次匹配:首先通过调用,然后再次通过调用。相反,您可能只需要调用Match,然后在返回的Match实例上,检查的值以确定是否存在任何匹配项。当然还有@hwnd所说的。只要在这里使用Regex.Match方法,如果您有多个字符串,请使用.Matches方法。谢谢。你能看看编辑过的帖子并说这是不是你的意思吗?你能提供这个不存在的字符串行吗?