Ham Burg
Ham Burg

Reputation: 79

Replace date in string with date format

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?

Upvotes: 2

Views: 803

Answers (3)

sihirbazzz
sihirbazzz

Reputation: 718

If you don't need to exactly use Regex then there are simple -and probably more effective- ways to do what you try.

As an example -I couldn't check code for typos as i write what i remember- :

//Method to Trying Parse the given string to DateTime.
public static DateTime TryParseStrToDate (string DateString)
{
  var date = new DateTime();
            
  bool b = DateTime.TryParse(DateString, date);
            
  return date;
}
            
/// To create a file name with your special formatting needs
public static string CreateLogFileName(DateTime TheDate, bool IncludeHour)
{
    if(TheDate == new DateTime())
    { 
       throw new ArgumentNullException("Date Should be valid"); 
    }
    
return $"log_{TheDate.Year}-{TheDate.Month} foo {IncludeHour?TheDate.Hour : string.Empty}.txt";
}

...//Method Codes to Save the log file

Upvotes: 0

zett42
zett42

Reputation: 27766

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.

Upvotes: 1

Leandro Bardelli
Leandro Bardelli

Reputation: 11578

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

Upvotes: 0

Related Questions