Home > Back-end >  Replace date's pattern as date
Replace date's pattern as date

Time:06-13

This is my input text:

Hello {login}, Today is: {yyyy-MM-dd}

I would like to replace the pattern of the date that is inside the parentheses with today's date that matches text format.

I don't want to replace {login}, I want only to replace those parts, that contains date format (patterns accepted by DateTime.Now.ToString())

var sample1 = "Hello {login}, today is: {yyyy-MM-dd}";
var sample1Resolved = ResolveDate(sample1);
// sample1Resolved should be: "Hello {login}, Today is: 2022-06-12"

var sample2 = "Hello {login}, today is: {yyyy.MM.dd}";
var sample2Resolved = ResolveDate(sample2);
// sample2Resolved should be: "Hello {login}, Today is: 2022.06.12"

var sample3 = "Hello {login}, today is: {yyyy,MM,dd}";
var sample3Resolved = ResolveDate(sample3);
// sample3Resolved should be: "Hello {login}, Today is: 2022,06,12"

var sample4 = "Hello {login}, current year is: {yyyy}";
var sample4Resolved = ResolveDate(sample4);
// sample4Resolved should be: "Hello {login}, current year is: 2022"

I created this

public static string ResolveDate(string input)
{
    return Regex.Replace(input, @"\{(.*?)\}", match =>
    {
        var parsedDate = DateTime.Now.ToString(match.Groups[1].Value);

        if (DateTime.TryParse(parsedDate, out DateTime date))
            return parsedDate;

        return match.Value;
    });
}

It works for sample1, sample2, sample3, but it doesn't work for sample4, because 2022 is not properly parsed using DateTime.TryParse. Any ideas how can I fix that?

CodePudding user response:

Change pattern to the appropriate one for the string.Format method.

string login = "Some Name";
var dateTime = DateTime.UtcNow;

string format = "Hello {0}, Today is: {1:yyyy-MM-dd}";

string result = string.Format(format, login, dateTime);
Console.WriteLine(result);

CodePudding user response:

Just add (?!login) into your regex expression so it doesn't match that {login} part.

About your approach, I think you could workout things differently, like using a specific keyword for user input (as you did with login), but here is a tip, when you have the exact format string you can use TryParseExact instead of TryParse:

public static string ResolveDate(string input) {
    return Regex.Replace(input, @"\{((?!login).*?)\}", match =>
    {
        var parsedDate = DateTime.Now.ToString(match.Groups[1].Value);

        if (DateTime.TryParseExact(parsedDate, match.Groups[1].Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
            return parsedDate;

        return match.Value;
    });
}

My output:

Hello {login}, today is: 2022-06-12
Hello {login}, today is: 2022.06.12
Hello {login}, today is: 2022,06,12
Hello {login}, current year is: 2022
  •  Tags:  
  • c#
  • Related