-2

regular expression that i want is to be used with Java. i have tried using previously designed regular expression but they are not serving the need

i have tried this version of regular expression:

^(((((0[1-9])|(1\d)|(2[0-8]))-((0[1-9])|(1[0-2])))|((31-((0[13578])|(1[02])))|((29|30)-((0[1,3-9])|(1[0-2])))))-((20[0-9][0-9]))|(29-02-20(([02468][048])|([13579][26]))))$
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
  • 2
    And I'm wondering why do you need a regular expression to validade this dateFormat instead of use the `SimpleDateFormat` ? – Jorge Campos May 23 '14 at 13:53
  • 1
    possible duplicate of [Regex to validate date format dd/mm/yyyy](http://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy), and also [Regular Expression to match valid dates](http://stackoverflow.com/questions/51224/regular-expression-to-match-valid-dates) – Oleg Estekhin May 23 '14 at 14:03
  • Give the context in which you want to parse a date. Are you reading from a text component or a string, and what do you want to do with the result? Regular expressions is the wrong way in any case. – user1803551 May 23 '14 at 14:03
  • @OlegEstekhin True, but that question was before Java 8 giving you a 1 line solution depending on what you want to do exactly. – user1803551 May 23 '14 at 14:05
  • Then just go and answer the old and existing question with a new solution instead of creating total duplicates just for the sake of a new answer. – Oleg Estekhin May 23 '14 at 14:06
  • @OlegEstekhin I did not ask the question nor did I answer it or am going to until the OP clarifies what they want to do because this is an obvious XY problem. – user1803551 May 23 '14 at 14:07

3 Answers3

1

don't use regex for date parsing, use the date parser, E.g SimpleDateFormat.parse()

Kent
  • 189,393
  • 32
  • 233
  • 301
0

Check string format by:

^[0-9]{2}-[0-9]{2}-[0-9]{4}$

Then validate your date using:

new SimpleDateFormat("dd-MM-yyyy").parse(yourDateString);
davioooh
  • 23,742
  • 39
  • 159
  • 250
0

At a quick glance, the following should work:

(0[1-9]|[1-2][0-9]|3[01])\-(0[1-9]|1[0-2])\-(\d{4})

At a second glance however you will find that this doesn't stop things like trying to match 31-02-2008, i.e.: that is the 31st of February, which is an invalid date.

As others suggested it is preferable to use something like SimpleDateFormat.parse() if possible, as it will cover the day/month variations, and is more likely to cover things like leap years and such.

Alan
  • 3,307
  • 1
  • 19
  • 22