简体   繁体   中英

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:

Field1:val1,Field2:val2,Field3:val3 and so on

where the val1, val2 or val3 can be datetime or alphamuneric value.

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

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*),? will split extract the key/value pairs from the input string directly to groups named key and value eg:

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. 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:

(?<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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM