首页 > 解决方案 > 在冒号周围拆分字符串

问题描述

您能否帮助将字符串拆分为围绕冒号分隔符的键值对。我遇到了麻烦。

例如。

"somekey:value1 value2 another:<value3 one_more:value4..value5"

输出

<"somekey", "value1 value2">
<"another", "<value3">
<"one_more", "value4..value5">

标签: c#.net-core

解决方案


你可以试试这个正则表达式。

string givenString =
@"key1:value1 value2 key2:<value3 key3:value4..value5";

Dictionary<string, string> result1 = Regex
          .Split(givenString, "([a-z0-9]+:)")
          .Skip(1)    // will skip the first empty                         
          .Select((item, index) => new {      
              value = item.Trim(),
              index = index / 2
          })
          .GroupBy(item => item.index)
          .ToDictionary(chunk => chunk.First().value.TrimEnd(':'),
                        chunk => chunk.Last().value);

推荐阅读