Reading a string from one char to another

  • A+
Category:Languages

I have the following string:

FB:77:CB:0B:EC:09{W: 0,623413, X: 0,015374, Y: 0,005306, Z: -0,781723}

I want to read out the values of W,X,Y,Z as a float/decimal. The values are not always the same length.

How can I read this string from one character to another without using relative positions?

 


I'd suggest matching the "inner" part with a regular expression, but removing the "outer" part manually first - just to keep the regex as simple as possible.

Here's a complete example, with a method that returns the result as a Dictionary<string, string>. It's not clear how you'd then want to convert the sample values you've given (e.g. "0,623413") into integers, but I'd treat that as a separate task from the initial parsing.

I'm assuming that it's fine to strip all trailing commas from values:

using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions;  class Test {     static void Main()     {         string input = "FB:77:CB:0B:EC:09{W: 0,623413, X: 0,015374, Y: 0,005306, Z: -0,781723}";         var parsed = Parse(input);         foreach (var entry in parsed)         {             Console.WriteLine($"Key = '{entry.Key}', Value = '{entry.Value}'");         }             }      static readonly Regex regex = new Regex(@"(?<key>[A-Z]+): (?<value>[-/d,]+)");     static IDictionary<string, string> Parse(string input)     {         int openBrace = input.IndexOf('{');         if (openBrace == -1)         {             throw new ArgumentException("Expected input to contain a {");         }         if (!input.EndsWith("}"))         {             throw new ArgumentException("Expected input to end with }");         }         string inner = input.Substring(openBrace + 1, input.Length - openBrace - 2);         var matches = regex.Matches(inner);         return matches.Cast<Match>()             .ToDictionary(match => match.Groups["key"].Value,                           match => match.Groups["value"].Value.TrimEnd(','));     } } 

Output:

Key = 'W', Value = '0,623413' Key = 'X', Value = '0,015374' Key = 'Y', Value = '0,005306' Key = 'Z', Value = '-0,781723' 

Converting those values to integers may be as simple as removing the commas, trimming leading zeroes, and then using int.Parse - but it really depends on what you want the results to be.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: