I am using the regular expression of the date for the format “MM/DD/YYYY” like
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
its working fine, no problem….here I want to limit the year between "1950" to "2050", how to do this, can anyone help me….
So the answer depends on how you want to accomplish the task.
Your current
Regexsearch pattern is going to match on most dates in the format “MM/DD/YYYY” in the 20th and 21st century. So one approach is to loop through the resulting matches, which are represented as string values at this point, and parse each string into aDateTime. Then you can do some range validation checking.(Note: I removed the beginning
^and ending$from your original to make my example work)This code outputs the following, noting that 1776 is not matched, the other two dates are, but only the last one is added to the list.
Although this approach has some drawbacks, such as looping over the results a second time to try and do the range validation, there are some advantages as well.
DateTimemethods in the framework are easier to deal with, rather than constantly adjusting theRegexsearch pattern as your acceptable range can move over time.Regexsearch pattern to be more inclusive, perhaps even getting all dates.Regexsearch pattern is easier to maintain, and also makes clear the intent of the code.Regexcan be confusing and tricky to decipher the meaning, especially for less experienced coders.Regexsearch patterns can introduce subtle bugs. Make sure you have good unit tests wrapped around your code.Of course your other approach is to adjust the
Regexsearch pattern so that you don’t have to parse and check afterwards. In most cases this is going to be the best option. Your search pattern is not returning any values that are outside the range, so you don’t have to loop or do any additional checking at that point. Just remember those unit tests!As @skywalker pointed out in his answer, this pattern should work for you.