gpt4 book ai didi

c# - 如何替换包含格式信息的字符串

转载 作者:行者123 更新时间:2023-11-30 22:04:58 25 4
gpt4 key购买 nike

我有一个 C# 字符串,其中包含我需要用有效数据替换并按定义格式化的信息。例如,这里有一些初始字符串的例子:

Here is my test [Date{yyyyMMdd}] string
Here is my test [Date{yyyy_MM_dd}] string

我需要在字符串中找到 [Date{yyyymmdd}] 或 [Date{yyyy_mm_dd}] 部分,并替换 {} 部分内定义的格式化日期。上面的示例将导致以下结果:

Here is my test 20140711 string
Here is my test 2014_07_11 string

我如何编写程序来找到括号中的字符串,然后使用它里面大括号中的格式信息?我可以使用以下正则表达式来找到我需要的部分,但我不知道如何使用它来获取我想要的输出并使用 {} 内的区域根据需要格式化日期:

(\[Date\{(?<format>.*)\}\])

最佳答案

您可以为 <a href="http://msdn.microsoft.com/en-us/library/ht1sxswy(v=vs.110).aspx" rel="noreferrer noopener nofollow">Regex.Replace</a> 使用重载需要一个代表来处理匹配:

string testString = "Here is my test [Date{yyyyMMdd}] string";
Regex.Replace(testString, @"(\[Date\{(?<format>.*)\}\])", match => DateTime.Now.ToString(match.Groups["format"].Value));

关于c# - 如何替换包含格式信息的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com