Reputation: 10943
How to convert the regex from
^((19|20)\\d\\d)(0?[1-9]|1[012])(0?[1-9]|[12][0-9]|3[01])? for 1900-2099
The above one works perfectly,just want change for date formats 1900-9999.So go for below one.
I tried like this it is not working
^(([19-99])\\d\\d)(0?[1-9]|1[012])(0?[1-9]|[12][0-9]|3[01])? for 1900-9999
What is wrong please guide me resolve this.
Upvotes: 0
Views: 2226
Reputation: 124215
Don't even use regex to validate integers range (it is maintenance hell later, just like you are having now). Instead parse your string to something more accurate like Date or integer and use <
<=
>
>=
operators.
int year = Integer.parseInt(yourYear)
if (year >= 1900 && year <= 9999){
//do your job here
}
But if you don't have a choice and you must do it with regex you can try with
19\\d\\d|[2-9]\\d\\d\\d
which you can visualize as
19xx <-> 1 9 \\d \\d
2xxx <-> [2-9] \\d \\d \\d
3xxx <-> [2-9] \\d \\d \\d
4xxx <-> [2-9] \\d \\d \\d
5xxx <-> [2-9] \\d \\d \\d
6xxx <-> [2-9] \\d \\d \\d
7xxx <-> [2-9] \\d \\d \\d
8xxx <-> [2-9] \\d \\d \\d
9xxx <-> [2-9] \\d \\d \\d
Little shorter regex could be 19\\d{2}|[2-9]\\d{3}
.
Upvotes: 5
Reputation: 22457
[19-99]
is a wrong usage of the character class operators [..]
. This part would match one character out of the set of 1
, 9
to 9
, or 9
(i.e., only 1
or 9
).
I have no idea why the top ("working") expression is so complicated. You can just use
\b(19|20)\d\d\b
for 1900-2099, and
\b19\d\d\b
for 1900-1999. Double-escape mybackslashes for use in a Java string.
(... After another question change)
and for 1900-9999, simply use
\b(19|[2-9]9)\d{2}\b
Upvotes: 0
Reputation: 3356
The expression could look like this:
^(19|[2-9]\\d)\\d{2}$
For explanation:
^
: start of string
(19|[2-9]\\d)
: either the value 19
or values 20
to 99
\\d{2}
: values 00
to 99
$
: end of string
Upvotes: 0