Brendan Vogt
Brendan Vogt

Reputation: 26048

Regular expression range that must not start at zero

I am trying to write a regular expression where only values from 1 thru 99 are allowed.

Valid values:

1
01
2
02
3
03
...
19
20
21
...
98
99

Everything else must throw an error like:

00
0
-1
1.0
1.
100

I currently have this:

^[1-9]([0-9]+$)

This is not working. It only accepts values from 10 and above.

Upvotes: 2

Views: 454

Answers (5)

Nikolay
Nikolay

Reputation: 329

This shoud work : ^(([0-9][1-9])|([1-9][0-9])|[1-9])$

Upvotes: 0

Equalsk
Equalsk

Reputation: 8214

Try this Regex:

^([1-9]|[1-9][0-9]|0[1-9])$/mg

Demo here Regex101

It uses the | operator which is equivalent to OR.

So basically this Regex is saying:

Is the number between 1 and 9?

OR

Is the first number between 1 and 9, and the second number between 0 and 9?

OR

Does the number begin with a 0 and end with a number between 1 and 9?

The flags on the end /mg just make it check each line for the demo, you may want to change or remove these.

Edit: For whatever reason I didn't see Kuba's answer. His is actually cleaner, but works in roughly the same way as this one should you have wanted an explanation.

Upvotes: 0

James Buck
James Buck

Reputation: 1640

/^(0?[1-9]|[1-9][0-9])$/gm

Demo here.

Upvotes: 0

CaHa
CaHa

Reputation: 1166

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

first part covers 1 to 9 and the 0x

second part is for everything between 10 and 99

Upvotes: 2

Kuba Wyrostek
Kuba Wyrostek

Reputation: 6221

This should do:

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

Upvotes: 4

Related Questions