获取正则表达式匹配列表

本文关键字:列表 正则表达式 获取 | 更新日期: 2023-09-27 18:19:23

我有一个字符串叫做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(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"answers"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();