Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match number between 1 and 31 with or without leading 0

I want to setup some validation on an <input> to prevent the user from entering wrong characters. For this I am using ng-pattern. It currently disables the user from entering wrong characters, but I also noticed this is not the expected behavior so I am also planning on creating a directive.


I am using

AngularJS: 1.6.1


What should the regex match

Below are the requirements for the regex string:

  • Number 0x to xx (example 01 to 93)
  • Number x to xx (example 9 to 60)
  • Characters are not allowed
  • Special characters are not allowed

Notice: the 'x' is variable and could be any number between 0 and 100.

The number on the place of 'x' is variable so if it is possible to create a string that is easily changeable that would be appreciated!


What I tried

A few regex strings I tried where:

1) ^0*([0-9]\d{1,2})$

--> Does match 01 but not 1
--> Does match 32 where it shouldn't

2) ^[1-9][0-9]?$|^31$

--> Does match 1 but not 01
--> Does match 32 where it shouldn't

For testing I am using https://regex101.com/tests.

What am I missing in my attempts?

like image 390
Mr.wiseguy Avatar asked Jan 13 '17 13:01

Mr.wiseguy


2 Answers

This should work:

^(0?[1-9]|[12][0-9]|3[01])$

https://regex101.com/r/BYSDwz/1

like image 29
georg Avatar answered Nov 15 '22 15:11

georg


If your aim is to match 0 to 100, here's a way, based on the previous solution.

\b(0?[1-9]|[1-9][0-9]|100)\b

Basically, there's 3 parts to that match...

0?[1-9] Addresses numbers 1 to 9, by mentionning that 0 migh be present

[1-9][0-9] covers number 10 to 99, the [1-9] representing the tens

100 covers for 100

Here's an example of it

Where you to require to set the higher boundary to 42, the middle part of the expression would become [1-3][0-9] (covering 10 to 39) and the last part would become 4[0-2] (covering 40 to 42) like so:

\b(0?[1-9]|[1-3][0-9]|4[0-2])\b
like image 56
Sebastien Dufresne Avatar answered Nov 15 '22 17:11

Sebastien Dufresne