cory.todd
cory.todd

Reputation: 516

Regex pattern for a number within a number

Can anyone think of a better way to write this? It works but it is a little ugly.

Input data looks like this: 125100001

The first two numbers are the year, next two are the week number, and last 5 are the serial. I want to validate that the week number is not over 52 for an angular input[number] pattern option. Basically just to leverage the $error field :)

So here it is:

^\d\d(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-2]){1}\d{5}$

Upvotes: 0

Views: 115

Answers (2)

zx81
zx81

Reputation: 41838

Use this:

^(\d{2})([0-4][1-9]|[1-5]0|5[12])(\d{5})$

Notes

  • The first set of parentheses (0[1-9]|1[0-2]) validates the month: 01-12
  • The second set of parentheses ([0-4][1-9]|[1-5]0|5[12]) validates the week: 01-52
  • If you wish, you can retrieve each component with groups 1, 2 and 2

Upvotes: 1

perreal
perreal

Reputation: 97928

Just for the week part:

[0-4]\d|5[0-2]

so the entire regex would be:

^\d\d([0-4]\d|5[0-2])\d{5}$

Upvotes: 0

Related Questions