首页 > 解决方案 > c#如何从包含格式的字符串中提取格式(例如string =“Printed on {0:dd MMM yyyy}”,我想要dd MMM yyyy

问题描述

如果我有一个包含以下格式的字符串(请注意,我无法更改此字符串格式)

var str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}"

我只需要提取格式,例如

"dd MMM yyyy HH:mm:ss"

我知道我可以使用字符串操作或正则表达式来做到这一点,但是有没有.Net 方法可以使用string/format等来做到这一点。例如,我不需要将给定的字符串插入到我需要提取该格式的格式中。

非常感谢

标签: c#.netstringdatetimeformat

解决方案


使用正则表达式

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";
            string pattern = @"{\d+:(?'date'[^}]+)";
            Match match = Regex.Match(str, pattern);
            string date = match.Groups["date"].Value;

没有正则表达式

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";

            string[] splitData = str.Split(new char[] { '{' });
            string date = splitData[1].Substring(splitData[1].IndexOf(":") + 1);
            date = date.Replace("}", "");

在打开和关闭大括号上拆分可节省一行代码

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";

            string[] splitData = str.Split(new char[] { '{', '}' });
            string date = splitData[1].Substring(splitData[1].IndexOf(":") + 1);

推荐阅读