FaisalAhmed
FaisalAhmed

Reputation: 3651

Regex to check if string contains year

I want a regex which matches this year separated with hyphen. Examples

1986-2004
2001-2007 

basically it should allow only 4 digit to each year and not less or more then that and it should be separated with hyphen.

What Regex i tried to build match till 1986-

^[0-9]{4}+[-]{1}+[0-9]*$ 

when i try some thing like this

^[0-9]{4}+[-]{1}+[0-9]{4}*$

{4} at the last year it gives pattern error. Please help me how can i add {4} at the end of the pattern

Upvotes: 2

Views: 1113

Answers (2)

Elvira  Parpalac
Elvira Parpalac

Reputation: 31

Your regex allows following years too: 8970-9047, 0120-0110, 0000-0000. May be will be better to use the pattern, that will check the boundaries. For example, something like this:

\b(18|20)\d{2}\b[-]\b(18|20)\d{2}\b

Upvotes: 0

Mureinik
Mureinik

Reputation: 312344

The * means "any number of times", which clashed with {4} which means "four times". Just drop the * and you should be OK:

^[0-9]{4}+[-]{1}+[0-9]{4}$

Upvotes: 2

Related Questions