user31673
user31673

Reputation: 13695

How to substitute string that contains formatting information

I have a c# string that I contains information that I need to substitute with valid data and format it as defined. For example, here are some examples for the initial strings:

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

I need to find in the string the [Date{yyyymmdd}] or the [Date{yyyy_mm_dd}] portions and substitute the Date formatted as defined inside of the {} section. The examples above would result in the following:

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

How can I program this to find the string in the brackets and then use the formatting information in the braces inside of it? I can use the following Regular Expression that will find the section I need but I don't know how I can use it to get the output I want and use the area inside of the {} to format the date as desired:

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

Upvotes: 2

Views: 62

Answers (1)

Ryan Emerle
Ryan Emerle

Reputation: 15811

You can use the overload for Regex.Replace that takes a delegate to handle the match:

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

Upvotes: 3

Related Questions