Regex: check date format in Europe with multiple delimiters

I want to check the European date formats, for example, "10.02.2012" or "10-02-2012". So I created the following regular expression:

/\d[0-9]{2}(.|-)\d[0-9]{2}(.|-)\d[0-9]{4}/ 

Unfortunately, I always get the message invalid, even if the date is in the correct format.

When I replace "(. | -)" with "." to check only dates separated by the point with which it works. So I guess the problem should be "(. | -)" Any ideas?

+4
source share
3 answers

It works correctly after minor changes:

 \d{2}(\.|-)\d{2}(\.|-)\d{4} 
  • "." must be shielded.

  • \ d is similar to [0-9], there is no need to repeat it.

http://regexr.com?326f2

+3
source

Please note that the answers so far provided using the \ d character class will allow dates such as 00.00.0000 or 99.99.9999 to pass. If you want to catch this, you need to use a more specific regex. The one below will allow the use of valid dates between 01/01/1900 and 12/31/2099

 ^([1-9]|0[1-9]|[12][0-9]|3[01])[-\.]([1-9]|0[1-9]|1[012])[-\.](19|20)\d\d$ 

If you want to allow any year from 0000 to 9999, you can change it to

 ^([1-9]|0[1-9]|[12][0-9]|3[01])[-\.]([1-9]|0[1-9]|1[012])[-\.]\d{4}$ 
+6
source

ok I see your problem ...

 /\d[0-9]{2}(.|-)\d[0-9]{2}(.|-)\d[0-9]{4}/ 

is redundant in that \ d matches [0-9], so in fact here you are matching 3 digits, not 2. Try

 /\d{2}(\.|-)\d{2}(\.|-)\d{4}/ 

or

 /[0-9]{2}(\.|-)[0-9]{2}(\.|-)[0-9]{4}/ 

but do not use both

+1
source

Source: https://habr.com/ru/post/1434786/


All Articles