常正则表达式是不是在现在看来似乎是使用合适的工具。
阅读周到职位的详细信息:https://softwareengineering.stackexchange.com/questions/223634/what-is-meant-by-now-you-have-two-problems
当一个简单的方案会做,用它!下面是一个方案,该方案将成功,只要冒号唯一属性和值之间发生解析结构,也不在他们
代码
static void Main(string[] args)
{
string data = "ATTRIBUTE: Value of this attribute,ATTRIBUTE2: Another value, but this one has a comma in it,ATTRIBUTE3:, another value,value1,ATTRIBUTE4:end of file";
Console.WriteLine();
Console.WriteLine("As an String");
Console.WriteLine();
Console.WriteLine(data);
string[] arr = data.Split(new[] { ":" }, StringSplitOptions.None);
Dictionary<string, string> attributeNameToValue = new Dictionary<string, string>();
Console.WriteLine();
Console.WriteLine("As an Array Split on ':'");
Console.WriteLine();
Console.WriteLine("{\"" + String.Join("\",\"", arr) + "\"}");
string currentAttribute = null;
string currentValue = null;
for (int i = 0; i < arr.Length; i++)
{
if (i == 0)
{
// The first element only has the first attribute name
currentAttribute = arr[i].Trim();
}
else if (i == arr.Length - 1)
{
// The last element only has the final value
attributeNameToValue[currentAttribute] = arr[i].Trim();
}
else
{
int indexOfLastComma = arr[i].LastIndexOf(",");
currentValue = arr[i].Substring(0, indexOfLastComma).Trim();
string nextAttribute = arr[i].Substring(indexOfLastComma + 1).Trim();
attributeNameToValue[currentAttribute] = currentValue;
currentAttribute = nextAttribute;
}
}
Console.WriteLine();
Console.WriteLine("As a Dictionary");
Console.WriteLine();
foreach (string key in attributeNameToValue.Keys)
{
Console.WriteLine(key + " : " + attributeNameToValue[key]);
}
}
输出:
作为字符串
ATTRIBUTE:此属性的值,ATTRIBUTE2:另一个值,但这个有一个逗号在它,ATTRIBUTE3 :,另一个值,值1,ATTRIBUTE4:文件
的端作为在阵列分割 ':'
{ “ATTRIBUTE”, “这个属性,ATTRIBUTE2" 的值,” 另一值,但是这一次在其中具有逗号,ATTRIBUTE3" , “另一个值,值1,ATTRIBUTE4”, “文件结束”}
作为字典
ATTRIBUTE:此属性的值
ATTRIBUTE2:另一个值,但是这个值有一个逗号
ATTRIBUTE3:,另一个值,值1
ATTRIBUTE4:文件结束
首先,问自己: “我想从我的输入检索什么” _ _。之后,你可以搜索如何做到这一点。一个好的观点,你注意到你的输入中的一个“模式”,你可以写一个正则表达式。 – Niitaku
我基本上想要检索一个干净的可访问的键/值存储,我可以分析或转换为列数据集。 答案可能只是:我需要学习正则表达式。 – econgineer
我不介意帮忙。 ;)你想使用哪种语言的正则表达式?您可以编辑您的问题以添加您在评论中撰写的所有信息。 – Niitaku