Home > Net >  Replace date in string with date format
Replace date in string with date format

Time:06-07

I want to replace patterns of date in string as date, so from this input:

log_{yyyy-MM} foo {HH}.txt

I should get:

log_2020-06 foo 11.txt

I created something like this:

public static string ReplaceDate(string input)
{
    var r = new Regex(@"\{(.*?)\}");
    var dateFormat = r.Match(input).Groups[1].Value; //Get the first matching group
    return r.Replace(input,DateTime.Now.ToString(dateFormat));
}

And with this input:

log_{yyyy-MM} foo.txt

My code returns (which is OK):

log_2022-06 foo.txt

but with this input:

log_{yyyy-MM} foo {HH}.txt

I get wrong output:

log_2022-06 foo 2022-06.txt

Any ideas how can I make it working with many groups?

CodePudding user response:

So the main idea is get every {group} and replace it with the parameters of: Microsoft Date Formats. But in any case I would suggest take consideration of your input, there are a lot of things can be wrong here: Regular expression to extract text between square brackets

string input = "log_{yyyy-MM} foo {HH}.txt";
DateTime now = DateTime.Now;

string[] results = Regex.Matches(input,@"\{.*?\}" ).Cast<Match>().Select(m => m.Value).ToArray(); 


foreach(string result in results) {
    input = input.Replace(result,now.ToString(result));
}

Fiddle: https://dotnetfiddle.net/cYdJtW

CodePudding user response:

Call the Regex.Replace() overload that allows you to pass a MatchEvaluator function:

return r.Replace( input, (match) => DateTime.Now.ToString( match.Groups[1].Value ) );

This way you can replace each date format pattern individually.

  • Related