Home > Software engineering >  Capture a Date value from a string
Capture a Date value from a string

Time:01-15

I have a string like below,

var text1 = "TEST 01DEC22 test";

I want to capture only the "01DEC22" date from the string; I tried and was successful if only the text contained the date only, as shown below.

 var text = "01DEC22";
 var results = Regex.Matches(text, @"^(([0-9])|([0-2][0-9])|([3][0-1]))(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{2}$").Cast<Match>().Select(x => x.Value).FirstOrDefault();

Kindly help me how to retrieve the value if it is contained within a string.

CodePudding user response:

If the dates are to be in two digits always, you may use below regex

((0[1-9])|([12]\d)|(3[01]))(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d

CodePudding user response:

As stated in the comments just remove the ^ and $ but you seem to have a careful way of checking for the day of the month instead of just \d?\d but with your method you still accept 0DEC22 as a date.

You can simplify the regex to this which only accepts valid days of the month:

(0?[1-9]|[12]\d|3[01])(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d

This would be even simpler if you aren't worried about invalid dates:

(\d?\d)(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d

  • Related