获取正则表达式匹配列表

时间:2014-08-25 12:49:11

标签: c# regex

我有一个名为line的字符串,我想使用正则表达式解析它:

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;
}

我不知道&#34; e&#34;和&#34; Key_2&#34;重复计数,我想将它们全部添加到数组中。 是否可以捕获所有这些?

//修改

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;
}

1 个答案:

答案 0 :(得分:0)

这可能有效:

var newArray = pattern.Matches( line ).OfType<Match>.Select( m => new { e = m.Groups["e"].Value, Key_2 = m.Groups["Key_2"].Value } ).ToArray();
相关问题