簡體   English   中英

獲取正則表達式匹配項列表

[英]Get list of regex matches

我有一個名為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;
}

我不知道“ 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM