解析一个key1=“;foo”;,key2=“;条”;CSV字符串到字典中(TKey,TValue)
本文关键字:CSV 字符串 TValue TKey 字典 foo 一个 key1 key2 | 更新日期: 2023-09-27 18:21:20
请使用以下字符串:
cbr="LACbtn",detnumber="1232700",laclvetype="ANN=x",laccalcrun="2014-09-10",lacbutton="Y",lacaccdays="00000000",lacentdate="2014-03-31",lacotdays="32.00",laclastent="2014-04-01",lacsrvdays="3,4",status="ok"
它的输出来自第三方SDK,我们需要访问.net应用程序中的值。
.net 2中有哪些对象可用于将此字符串解析为Dictionary(Of TKey, TValue)
?
例如,我们希望使用密钥名称获取值,例如:
Dim X = Whatever("detnumber") '#### Where X would then contain "1232700"
我开始用逗号分隔手动代码,但当","&"="存在于引用的值中,例如:key1="foo,bar",key2="hello=Dorothy!"
&我心想,一定有什么东西已经存在,可以解析这种类型的字符串?
我只是什么都没找到。
在vb.net或c#中的建议都可以。
字符串规则:
文档化有点糟糕(即,我还不知道如何处理值中的双引号),但我可以确认以下内容:
- 密钥从不被引用
- 键从不包含空格
- 逗号可以存在于值中:
Key="Hello: something"
- 等号可以存在于值中:
Key="something=something"
- 值总是带引号的,空值总是
Key=""
- 一个键=一个值,一个键的值永远不会超过一个
- 值之外不存在空白
- 键是可变的,可以被称为任何东西,甚至可以存在于值中
好的,考虑到您对输入字符串格式有一些严格的规则,这应该是:
public static Dictionary<string, string> GetInputKeyValuePairs(string input)
{
var inputKeysAndValues = new Dictionary<string, string>();
if (string.IsNullOrWhiteSpace(input)) return inputKeysAndValues;
const char keyValueDelimiter = '=';
const char itemDelimeter = ',';
const char valueContainer = '"';
var currentKey = string.Empty;
var currentValue = string.Empty;
var processingKey = true;
var processingValue = false;
foreach (var character in input)
{
if (processingKey)
{
// Add characters to currentKey until we get to the delimiter
if (character == keyValueDelimiter) processingKey = false;
else currentKey += character;
continue;
}
if (processingValue)
{
// Add characters to the currentValue until we get to the delimeter
if (character == valueContainer) processingValue = false;
else currentValue += character;
continue;
}
if (character == itemDelimeter)
{
// We're between items now, so store the current Key/Value, reset
// them to empty strings, and set the flag to start processing a key.
inputKeysAndValues[currentKey] = currentValue;
currentKey = currentValue = string.Empty;
processingKey = true;
continue;
}
if (character == valueContainer)
{
// We're at the first quote before a value, so ignore
// it and set the flag to start processing a value
processingValue = true;
continue;
}
}
// Add the last key/value
if (currentKey != string.Empty) inputKeysAndValues[currentKey] = currentValue;
return inputKeysAndValues;
}