Adam Ramadhan
Adam Ramadhan

Reputation: 22820

how to get 1-100 using regex

I'm trying to get something like:

    Hello, 0 ( dont get )
    Hello2, 100 ( get )
    hello3, 82 ( get )
    hello< 132 ( dont get )

I've made something like this so far:

[a-zA-Z]{1,255},([0-9]{1,3})(?<![0])

But it can't get 132 and 100. How can I fix this?

Upvotes: 6

Views: 17056

Answers (4)

Noam Manos
Noam Manos

Reputation: 16990

You can also check it by combining regex and arithmetical condition:

1) String is a number: regex match [0-9]+

AND

2) The number is between 1..100.

For example, in bash:

N=100

[[ "$N" =~ ^([0-9]+)$ ]] && (( $N>0 && $N<=100 )) && echo YES || echo NO
# YES

[[ "$N" =~ ^([0-9]+)$ && "$N" -le "100" && "$N" -gt "0" ]] && echo YES || echo NO
# YES


N=0

[[ "$N" =~ ^([0-9]+)$ ]] && (( $N>0 && $N<=100 )) && echo YES || echo NO 
# NO

[[ "$N" =~ ^([0-9]+)$ && "$N" -le "100" && "$N" -gt "0" ]] && echo YES || echo NO
# NO

Upvotes: 0

Ved
Ved

Reputation: 12103

Try this.. It will match 1 to 99 or 100. Number greater than 100 will be invalid.

(?:\b|-)([0-9]{1,2}|100)\b

Fiddle Link.. https://regex101.com/r/mN1iT5/462

Upvotes: 1

CAFxX
CAFxX

Reputation: 30331

Why not keeping it simple?

^[a-zA-Z]{1,255}, (100|[1-9][0-9]|[1-9])$

or better yet

^[a-zA-Z]{1,255}, (100|[1-9][0-9]?)$

note: this won't match prepended zeros e.g. "Hello, 00001". It can be easily extended, though:

^[a-zA-Z]{1,255}, 0*(100|[1-9][0-9]?)$

Upvotes: 4

Benoit
Benoit

Reputation: 79215

Try this regex which matches a number of 1 or 2 digits, or 100:

\d{1,2}(?!\d)|100

Upvotes: 17

Related Questions