【问题标题】:How to substitute string that contains formatting information如何替换包含格式信息的字符串
【发布时间】:2014-07-11 17:42:04
【问题描述】:

我有一个 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>.*)\}\])

【问题讨论】:

    标签: c# .net regex string replace


    【解决方案1】:

    您可以使用@987654321@ 的重载,它需要一个委托来处理匹配:

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

    【讨论】:

    • +1 用于替换中的 lambda(对不起,我的意思是委托):)
    猜你喜欢
    • 2021-11-23
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2014-12-17
    • 2017-11-19
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多