c# - 在冒号周围拆分字符串
问题描述
您能否帮助将字符串拆分为围绕冒号分隔符的键值对。我遇到了麻烦。
例如。
"somekey:value1 value2 another:<value3 one_more:value4..value5"
输出
<"somekey", "value1 value2">
<"another", "<value3">
<"one_more", "value4..value5">
解决方案
你可以试试这个正则表达式。
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);
推荐阅读
- autodesk-forge - 如何从 zip 打开 .rvt 文件?
- azure - Azure 数据共享资源在尝试从 terraform 预配时抱怨标记应全部为小写
- machine-learning - PyTorch 中自定义后向函数的损失 - 简单 MSE 示例中的爆炸损失
- r - R 在启用过滤器的情况下读取 xlsx 问题
- c++ - 为什么即使在删除后std :: string也会导致类中的内存泄漏
- javascript - 通过节点检查系统声级?
- java - 当 Spring Boot 应用程序收到第一个并行请求时,Tomcat 停止服务
- php - 参数 #1 ($parser) 必须通过引用传递
- c - 为什么我的函数不能接受 char 变量类型?
- go - 如何在另一个文件中使用 swaggo 中的类型定义?