How does this time Regex Work?
I've just inherited a projected with a lot of client side validation.
In this I have found a regex checker, as 开发者_如何学JAVAexpected without a comment in sight. I'll admit regex is definitely one of my failing points. (In Javascript!)
var myRegxp = /(([0]*[1-9]{1})|([1]{1}[0-2]{1}))(\/{1})((19[0-9]{2})|([2-9]{1}[0-9]{3}))$/;
if (!myRegxp.test(args.Value))
{//do fail stuff here};
I'm pretty sure from the rest of the page that it's supposed to be checking for some sort of date format. Would this pass MM/YYYY. From some early testing, it almost does it.
If this regex doesn't match MM/YYYY, what would be the best way to do this?
Any advice from the regex masters would be appreciated.
It should end with MM/YYYY (where MM is 1-12 and YYYY is 1900-9999)
(matching month)
([0]*[1-9]{1})
zero or more occurences of '0', and one occurence of 1-9
Example match: 01
OR
([1]{1}[0-2]{1})
1 match of '1', 1 match of 0-2
Example match: 10
Second part (year), first it literally match '/' with:
(\/{1})
Then the year:
((19[0-9]{2})
One match of '/', 19 and two matches of 0-9 (looks like a year in the range 1900-1999)
Example match: 1900
OR
([2-9]{1}[0-9]{3})
1 match of 2-9 and thee matches of 0-9 (looks like a year in the range 2000-9999
Example match: 2000
A simplified RE:
var myRegExp = /^(0[1-9]|1[0-2])\/(19\d{2}|[2-9]\d{3})$/;
Note: \d
is a character class for 0-9
. I've removed parentheses used for grouping because these are not used in myRegExp.test
. Replaced Replaced [0]*
by 0?
since it should not match 0000001/2010
, but it should match 1/2010
.[0]*
by 0
since it should literally match 01
and not 1
. The ^
and $
are anchors, causing it to match from begin to end. When leaving these out, this RE would match any text containing MM/YYYY.
I would agree - it is checking dates in the format MM/yyyy.
It allows any number of leading zeros on the month. It allows years matching 19xx
or anything else starting with a digit between 2
and 9
inclusive. This means that it allows anything up to 9999 for the year :)
精彩评论