c# - 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
等来做到这一点。例如,我不需要将给定的字符串插入到我需要提取该格式的格式中。
非常感谢
解决方案
使用正则表达式
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);
推荐阅读
- python - ModuleNotFoundError:没有以 virtualenv 命名的模块,需要了解如何为生产构建它
- python - 切片张量的每个原始数据
- sql - SQL - 多部分标识符错误:无法绑定多部分标识符“OBDATE.SUMMARY_BLOCK_ID”
- javascript - Javascript数组对象到逗号分隔的单行数组
- python - 轻松阅读行“参数”
- vb.net - 如果出现带有特定数字的标签,如何将图片框从可见更改为不可见?
- javascript - 在 React 中创建加载超时页面
- java - Android toasts 有时不显示应用程序首次启动的时间
- node.js - 使用临时 Docker 映像运行 NodeJs 二进制文件
- node.js - Node.js https 请求卡住