【问题标题】:Combine two regex groups into a key/value pair object?将两个正则表达式组组合成一个键/值对对象?
【发布时间】:2010-12-25 07:25:34
【问题描述】:

假设我有以下字符串

Type="Category" Position="Top" Child="3" ABC="XYZ"....

还有 2 个正则表达式组:键和值

Key: "Type", "Position", "Child",...
Value: "Category", "Top", "3",...

我们如何将这 2 个捕获的组组合成键/值对对象,如 Hashtable?

Dictionary["Type"] = "Category";
Dictionary["Position"] = "Top";
Dictionary["Child"] = "3";
...

【问题讨论】:

    标签: c# regex join regex-group captured-variable


    【解决方案1】:

    我的建议:

    System.Collections.Generic.Dictionary<string, string> hashTable = new System.Collections.Generic.Dictionary<string, string>();
    
    string myString = "Type=\"Category\" Position=\"Top\" Child=\"3\"";
    string pattern = @"([A-Za-z0-9]+)(\s*)(=)(\s*)("")([^""]*)("")";
    
    System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(myString, pattern);
    foreach (System.Text.RegularExpressions.Match m in matches)
    {
        string key = m.Groups[1].Value;    // ([A-Za-z0-9]+)
        string value = m.Groups[6].Value;    // ([^""]*)
    
        hashTable[key] = value;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2017-04-12
      相关资源
      最近更新 更多