我建议先手动删除“外部”部分,然后再使用正则表达式匹配“内部”部分,这样可以使正则表达式尽可能简单。
以下是一个完整的示例,使用一种返回结果为Dictionary<string, string>
的方法。不清楚如何将给出的示例值(例如“0,623413”)转换为整数,但我认为这应该作为初始解析的一个独立任务。
我假设从值中去除所有尾随逗号也是可行的:
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(','));
}
}
输出:
Key = 'W', Value = '0,623413'
Key = 'X', Value = '0,015374'
Key = 'Y', Value = '0,005306'
Key = 'Z', Value = '-0,781723'
将这些值转换为整数可能很简单,只需去掉逗号,修剪前导零,然后使用int.Parse
- 但这真的取决于您想要的结果。
W = 0
,X = 0
,Y = 0
和Z = 0
? - Kristoffer Lerbæk Pedersen