gpt4 book ai didi

c# - 将两个正则表达式组合成一个键/值对对象?

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:11 25 4
gpt4 key购买 nike

假设我有以下字符串

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

还有 2 个正则表达式组:Key 和 Value

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

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

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

最佳答案

我的建议:

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

关于c# - 将两个正则表达式组合成一个键/值对对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4529608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com