PegasusFantasy
PegasusFantasy

Reputation: 113

Regex to match any integer greater than 1

I recently just picked up on regex and I am trying to figure out how to match the pattern of any numbers greater than 1. so far I came up with

[2-9][0-9]*

But it only works with the leftmost digit not being 1. For example, 234 works but 124 doesn't.

So what am I trying to achieve is that a single digit of 1 shouldn't be matched and any integer greater than it should.

Upvotes: 7

Views: 31447

Answers (3)

Tomáš Nedělka
Tomáš Nedělka

Reputation: 219

Use this

^[2-9]|[1-9]\d+$

See example here

Upvotes: 4

Rahul
Rahul

Reputation: 2738

You should be using alteration to define two categories of numbers.

  1. Less than 10.
  2. Greater than or equal to 10.

Regex: ^(?:[2-9]|\d\d\d*)$

Explanation:

[2-9] is for numbers less than 10.

\d\d\d* is for numbers greater than or equal to 10.

Regex101 Demo

Alternate solution considering preceding 0

Regex: ^0*(?:[2-9]|[1-9]\d\d*)$

Regex101 Demo

Upvotes: 14

pradosh nair
pradosh nair

Reputation: 945

This should do the trick. [0]*([2-9]+|[1-9][0-9][0-9]*)

Upvotes: 5

Related Questions