简体   繁体   中英

Regex for conditional replace to add leading zeros in a date

I have a list of dates in dd/mm/yyyy format, except some of the days and months are only a single digit. For example,

14/09/2019 - dd/mm/yyyy (correct)
1/10/2018 - d/mm/yyyy (should be 01/10/2018)
1/2/2018 - d/m/yyyy (should be 01/02/2018)

I want to convert all these dates to the accepted form which is dd/mm/yyyy .

I am only suppose to use REGEX here. Also I think I will need conditional regex replace here.

The pseudo code would be like :

  1. If the date is 1/10/2018 then format it to 01/10/2018 .
  2. If the date is 1/2/2018 then format it to 01/02/2018 .

Sorry, but I don't have any code to demonstrate this. I am stuck with this.

Use C#'s regex replace match evaluator , which is a delegate operation which is run everytime a match occurs.

For this, every time a match is hit, convert what was found to the format desired:

var text = @"1/2/2018";

Regex.Replace(text,
              @"\d?\d/\d?\d/\d\d\d\d",
              new MatchEvaluator((mtch) => 
                         DateTime.Parse(mtch.Groups[0].Value).ToString("MM/dd/yyyy")));

Replace returns this string "01/02/2018" ;


Note that I handle only one situation, one can expand the above delegate to read the current match and determine the return format needed.

You can use this method to check your date formats one by one

string convertDateToAcceptedFormat(string inputDate)
{
    Regex patternDDMMYYYY = new Regex(@"^(\d\d\/){2}\d{4}$");
    if (patternDDMMYYYY.Match(inputDate).Success)
        return inputDate;

    Regex patternDMMYYYY = new Regex(@"^\d\/\d\d\/\d{4}$");
    if (patternDMMYYYY.Match(inputDate).Success)
        return "0" + inputDate;

    Regex patternDMYYYY = new Regex(@"^(\d\/){2}\d{4}$");
    if (patternDMYYYY.Match(inputDate).Success)
        return "0" + inputDate.Substring(0,2) + "0" + inputDate.Substring(2);

    throw new Exception("Input date doesn't match any pattern");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM