user736893
user736893

Reputation:

Regex only allow x integers?

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

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

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 string

var 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

Iłya Bursov
Iłya Bursov

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

rgbflawed
rgbflawed

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

  • So we're doing the start of the string with: ^
  • Then 14 numbers 0-9
  • Then an optional group starting with a period and then up to three numbers (I'm assuming a period and then no numbers after wouldn't be acceptable. This is in contrast to what you posted)
  • A hyphen
  • Four numbers
  • Then the end of the string with: $

Upvotes: 1

euvl
euvl

Reputation: 4786

Try:

^(\d{14})(\.\d{0,3})?-(\d{4})$

Upvotes: 1

Related Questions