Question

I need a regular expression that can handle these date formats:

  • 2010-1-1
  • 2010-6-01
  • 2010-06-1
  • 10-10-2010
  • 10/10/2010
  • 2010/10/10

Is this possible or would I be better off creating multiple regular expressions for each format?

Was it helpful?

Solution

You can use a pipe (\|) to combine regular expressions, so as long as you can write a regex for each of these, you can paste them all together, e.g. this ought to match the first two dates: "\([12][0-9][0-9][0-9]-[1-9]-[1-9]\|[12][0-9][0-9][0-9]-[0-9]-0[1-9]\)" (You haven't clearly specified the formats, so this probably needs to be generalized for your actual problem.)

However, you've got some bigger questions you might need to consider.

What exactly does 10-11-2010 mean? Is that October 11, or November 10?

Are you assuming only valid dates? What are you going to do about 2010-1-32? What about 2010-2-29?

OTHER TIPS

You'd better to use different format validators with |, like:

/\b[\d]{4}-[\d]-[\d]\b
|
\b[\d]{4}-[\d]{1,2}-[\d]{1,2}\b
|
\b[\d]{2}-[\d]{2}-[\d]{4}\b
|
\b[\d]{2}\/[\d]{2}\/[\d]{4}\b
|
\b[\d]{4}\/[\d]{2}\/[\d]{2}\b/x

but please, note, that validate date and find it occurrence are not same issues. All your dates are valid dates in terms of standard strtotime - so you can use that fact to validate (not search) your dates.

try \d{2,4}[-/]\d{1,2}[-/]\d{1,4} http://regexr.com?36goq - see in action

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top