Reputation:
I have some dates that look like this:
20160517124945-0600
20160322134822.410-0500
20160322134822-0500
I used RegexMagic to find this regex:
(?:[0-9]+){14}\.?(?:[0-9]+){0,3}-(?:[0-9]+){4}
The problem is it also accepts things like this:
20160322134822-05800
or
20160323542352352352134822-0500
Apparently {}
doesn't mean what I thought it did. How can I ensure I can only enter 14 digits before the -
(or optional .
) and 4 after?
Upvotes: 1
Views: 140
Reputation: 626826
Note that your regex did not function as expected because (?:[0-9]+){0,3}
means match 1 or more digits zero, one, two or three times. That means, it matched any amount of digits.
It seems you need an optional group for the .
followed with 1+ digits and you need to replace +
with the limiting quantifiers:
^\d{14}(?:\.\d+)?-\d{4}$
See the regex demo.
Explanation:
^
- start of string (we need to ensure we only match 14 first digits before .
or -
)\d{14}
- 14 digits(?:\.\d+)?
- 1 or 0 sequences of .
+ 1 or more digits-
- a hyphen \d{4}
- 4 digits$
- end of stringvar re = /^\d{14}(?:\.\d+)?-\d{4}$/;
var strs = ['20160517124945-0600', '20160322134822.410-0500', '20160322134822-0500', '20160322134822-05800','20160323542352352352134822-0500'];
for (var s of strs) {
document.body.innerHTML += s + ": " + re.test(s) + "<br/>";
}
Upvotes: 2
Reputation: 24146
I suppose you could simplify your regexp like this:
^(\d{14})(\.\d{3})?(-\d{4})$
test https://regex101.com/r/lF9gX0/1
Upvotes: 0
Reputation: 2137
Here's my version:
^[0-9]{14}(\.[0-9]{1,3})?-[0-9]{4}$
For some reason I always like using [0-9] instead of \d
Upvotes: 1