[英]Parse string like Field1:val1,Field2:val2,Field3=val3 in c#
I want to parse a string return from a toString method of a class in c# with pattern like: 我想用类似的模式解析c#中类的toString方法的字符串返回:
Field1:val1,Field2:val2,Field3:val3 and so on Field1:val1,Field2:val2,Field3:val3等
where the val1, val2 or val3 can be datetime or alphamuneric value. 其中val1,val2或val3可以是日期时间或alphamuneric值。
Please suggest any standard approach to do it. 请提出任何标准方法。
This is what i will do: 这就是我要做的:
String data = "Field1:val1,Field2:val2,Field3=val3";
//split data into array of string with format like "key:value" or "key=value"
String[] keyValues = data.Split(',');
//for each string get the value and the key
foreach (var keyValue in keyValues)
{
var pair = keyValue.Split(':', '=');
var key = pair[0];
var value = pair[1];
var parsedValue = ParseValue(value);
}
private object ParseValue(string value)
{
//Parsing string to various type of object is another problem to face
}
Try using Split , eg 尝试使用Split ,例如
String data = "Field1:val1,Field2:val2,Field3=val3";
// items is the array of {"Field1", "val1", "Field2", "val2"...}
String[] items = data.Split(',', ':', '='); // <- Put all separators here
Then parse the values if need: 然后根据需要解析值:
for (int i = 0; i < items.Length; ++i) {
if (i % 2 == 0) { // <- Field Name
String field = items[i];
...
}
else { // <- Value
DateTime value = DateTime.Parse(items[i]); // <- Some kind of parsing; see also ParseExact, TryParse
...
}
}
While you can split the string manually and parse the values, it's far faster to use a regular expression to extract all pairs at once. 尽管您可以手动拆分字符串并解析值,但是使用正则表达式一次提取所有对的速度要快得多。 In this particular case, it's also less complicated. 在这种特殊情况下,它也不太复杂。
The pattern (?<key>\\w*)[:=](?<value>\\w*),?
模式(?<key>\\w*)[:=](?<value>\\w*),?
will split extract the key/value pairs from the input string directly to groups named key
and value
eg: 将直接从输入字符串中提取键/值对拆分为名为key
和value
组,例如:
var searchInput = "Field1:val1,Field2:val2,Field3=val3";
var regex = new Regex(@"(?<key>\w*)[:=](?<value>\w*),?");
var matches = regex.Matches(searchInput);
foreach (Match match in matches)
{
var key = match.Groups["key"].Value;
var val= match.Groups["value"].Value;
Console.WriteLine("Key: {0} Value: {1}",key,val);
}
To parse the values, you can use DateTime.TryParse to convert the value to a datetime. 若要解析值,可以使用DateTime.TryParse将值转换为日期时间。 If this fails, you can treat it as a string, eg: 如果失败,则可以将其视为字符串,例如:
DateTime parsedDate;
object parsedValue;
if (DateTime.TryParse(val, out parsedDate) )
parsedValue=parsedDate;
else
parsedValue=val;
In this case you have to modify the original regex to include the date separators in the value
pattern: 在这种情况下,您必须修改原始正则表达式以在value
模式中包括日期分隔符:
(?<key>\w*)[:=](?<value>[\w-:]*),?
If the =
separator was added in error, you can remove it from the pattern: 如果错误添加了=
分隔符,则可以将其从模式中删除:
(?<key>\w*)[:](?<value>[\w-:]*),?
This can all be cleaned up a bit using LINQ and anonymous types to get just the key/value pairs: 可以使用LINQ和匿名类型将其全部清理干净,只获取键/值对:
public static object DateOrString(string input)
{
if (String.IsNullOrWhiteSpace(input))
return input;
DateTime parsedDate;
if (DateTime.TryParse(input, out parsedDate))
return parsedDate;
return input;
}
...
var searchInput = "Field1:val1,Field2:val2,Field3:val3,Field4:2013-12-11T01:00:00";
var regex = new Regex(@"(?<key>\w*)[:=](?<value>[\w-:]*),?");
var matches = regex.Matches(searchInput);
var pairs = from Match match in matches
select new {
Key = match.Groups["key"].Value,
Value = DateOrString(match.Groups["value"].Value)
};
The pairs can now be converted to a Dictionary, a List, or whatever other structure is suitable. 现在可以将这些对转换为字典,列表或任何其他合适的结构。
Printing the pairs from the last example produces this: 打印最后一个示例中的对将产生以下结果:
Key: Field1 Value: val1
Key: Field2 Value: val2
Key: Field3 Value: val3
Key: Field4 Value: 11/12/2013 1:00:00 am
A .NET Fiddle of the code is here 代码的.NET小提琴在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.