Home > Net >  How to parse date in string without spaces in C#?
How to parse date in string without spaces in C#?

Time:03-19

Tried this code, it is parsing only 01/03/2022, for some reason it is not working for 26/03/2022

        string RegexDateTimeLicenseTemplate = @"\b([0-9]{2})[./-]([0-9]{2})[./-]([0-9]{4}|[0-9]{2})";
        var dateRegexTemplate = new Regex(RegexDateTimeLicenseTemplate);
        List<DateTime> dateTimes;
        string[] formats = { "dd/MM/yyyy"};
        plainText = @"ףמ-01/03/2022עד26/03/2022המטו";

        dateTimes = dateRegexTemplate.Matches(plainText).Select(x => DateTime.ParseExact(x.Value,
            formats,
            CultureInfo.InvariantCulture)).ToList();

enter image description here

CodePudding user response:

From what I can see in the example, the date might actually be surrounded by word characters, hence the word boundaries should not be there. Also, your pattern should allow for 1 or 2 digits in the day or month. Putting this together, I suggest the following pattern:

([0-9]{1,2})[./-]([0-9]{1,2})[./-]([0-9]{4}|[0-9]{2})
  • Related