Ricky
Ricky

Reputation: 7889

Regex with a maximum value

I have the following RegEx:

(^\d{1,3}$)|(\d{1,3})\.?(\d{0,0}[0,5])

This accepts any .5 increment of a number.

I want to add a range to this number of 13.5. Ideally, .5 should be valid to.

So, anything from .5 to 13.5, in .5 increments.

Examples allowed:

.5
4
12.5
13.5

Not allowed:

.56
3.45
14
14.5

Upvotes: 0

Views: 40

Answers (2)

revo
revo

Reputation: 48741

Your current regex has some big issues e.g. [0,5] doesn't mean either 0 or 5 but a 0, , or 5. Try the following regex instead:

^(?=.)(?:\d|1[0-3])?(?:\.5)?$

See live demo here

Based on your given allowed examples it matches 12 but doesn't match 12.0. If you want to match 12.0 as well you have to replace \.5 with \.[05]:

^(?=.)(?:\d|1[0-3])?(?:\.[05])?$

Note: postive lookahead (?=.) ensures that an empty match doesn't occur.

Upvotes: 1

Ledhund
Ledhund

Reputation: 1236

^([0-9]|1[0-3])?(\.[05])?$

This works for your given examples

Upvotes: 1

Related Questions