2

and Thanks. I created a

/^(19|20)([0-9]{2})-([0-9]{2}|0[0-9]{1})-([0-9]{2}|0[0-9]{1})$/g

Pattern in js but didnt work in browser. I tested Here. Working but in browser js not

Veyis Aliyev
  • 313
  • 2
  • 11

3 Answers3

2

Following regex should do the expected check.

\((19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))\
AZ_
  • 3,094
  • 1
  • 9
  • 19
  • I can understand the downvote. But 2018-02-31 is not a valid date either and your regex will still output that as a date. If OP wants a regex which does date validation too then it will be considerably harder! Leap years and the like will have to be taken into account. I'd appreciate a downvote removal. – Vqf5mG96cSTT Apr 05 '19 at 04:39
  • surely left Feb out, cuz it would be quite too much to be done with regex, that does not mean to have anything. however, removed downvote and this is not the place to reply the comment of somewhere else :) – AZ_ Apr 05 '19 at 06:35
1

You should be able to write your regex as the one below.

(19|20)\d{2}-\d{2}-\d{2}

See this JS code snippet:

var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);

console.log(result[0]);

Depending on what string you are using to match the regex on it could be that using ^ and $ is causing you trouble. Using ^ asserts the position at the start of the line. And using $ asserts the position at the end of the line. This of course means that it won't match if your string is " 1999-01-01 " with spaces or any other text on that same line.

Be advised that if you want it to work for any year and not just 1900 up to 2099 you have to use the one below.

\d{4}-\d{2}-\d{2}

On top of this do note that this captures anything that looks like a date e.g. 2099-99-99 will still be captured but is not a valid date. If you want date validation your regex will look considerably harder, see Regex to validate date format dd/mm/yyyy for an example with leap years and the like. Depending on your use case it might be easier to let Javascript do the validation.

Vqf5mG96cSTT
  • 2,561
  • 3
  • 22
  • 41
0

Thats is worked. Thanks.

var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);

console.log(result[0]);
Veyis Aliyev
  • 313
  • 2
  • 11