Nilzone-
Nilzone-

Reputation: 2786

Regex to match a specific date format in JAVA

I want to make sure a date is one of the following formats:

DD.MM.YYYY
DD-MM-YYYY
DD/MM/YYYY

My regex-pattern looks like this:

"^[0-9]{2}['/''-''.'][0-9]{2}['/''-''.'][1-9][0-9]${3}"

I thought this code above says:

  1. -start by looking at numbers 0-9 (do this twice)
  2. -followed by either '/''-''.'
  3. -followed by 0-9 two more times.
  4. -followed by either '/''-''.' (again)
  5. End with a year (4 numbers) that start with 1

But it returns false on e.g. 16-10-1990

I'm pretty new to regex, so any help on this would be much appreciated!

Upvotes: 0

Views: 127

Answers (2)

Colin
Colin

Reputation: 4135

Here's the corrected expression. I removed the single quotes from the character classes, escaped the dash and moved the "$" at the end.

^[0-9]{2}[/\-.][0-9]{2}[/\-.][1-9][0-9]{3}$

To ensure that the same character is used as a divider in both spaces, you can either do three OR-ed expressions:

^([0-9]{2}\.[0-9]{2}\.[1-9][0-9]{3}|[0-9]{2}-[0-9]{2}-[1-9][0-9]{3}|[0-9]{2}/[0-9]{2}/[1-9][0-9]{3})$

...or do a string replace on the '/', '-' and '.' characters so they're consistent (e.g. convert them all to dashes) before testing against the expression.

Upvotes: 3

54l3d
54l3d

Reputation: 3973

This should work

^[0-9]{2}[-./][0-9]{2}[-./]1[0-9]{3}$

^ begin of string
2 digits
- or . or /
2 digits
- or . or /
1
3 digits
$ end of string

Upvotes: 2

Related Questions