You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何正确分割含时间格式的冒号分隔字符串?

问题场景

需要分割如下字符串:

PublishDate: "2011-03-18T11:08:07.983"

使用C#的Split方法:

str.Split(new[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries)

得到的结果是:PublishDate、2011-03-18T11、08、07.983,但期望结果是:PublishDate、2011-03-18T11:08:07.983。

解决方案

方法1:仅分割第一个冒号及后续空格

核心思路是只拆分键和值之间的第一个冒号,避免误拆日期里的冒号,再处理掉多余的引号和空格:

var str = "PublishDate: \"2011-03-18T11:08:07.983\"";
var colonIndex = str.IndexOf(':');
var result = new[]
{
    str.Substring(0, colonIndex),
    str.Substring(colonIndex + 1).Trim().Trim('"')
};
// 最终结果:["PublishDate", "2011-03-18T11:08:07.983"]

方法2:使用正则精准匹配

通过正则表达式匹配键名和带引号的日期值,确保不会拆分日期内部的符号:

using System.Text.RegularExpressions;

var str = "PublishDate: \"2011-03-18T11:08:07.983\"";
var match = Regex.Match(str, @"^(\w+):\s*""([^""]+)""$");
if (match.Success)
{
    var key = match.Groups[1].Value;
    var dateValue = match.Groups[2].Value;
    // key: PublishDate,dateValue: 2011-03-18T11:08:07.983
}

方法3:按固定分隔符组合分割

如果键和值之间的分隔符固定为": "(冒号加空格),直接用该组合作为拆分依据:

var str = "PublishDate: \"2011-03-18T11:08:07.983\"";
var parts = str.Split(new[] { ": " }, StringSplitOptions.None);
parts[1] = parts[1].Trim('"');
// 最终结果:["PublishDate", "2011-03-18T11:08:07.983"]

内容的提问来源于stack exchange,提问作者user19839948

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:39:19