Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match any integer greater than 1

Tags:

regex

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.

like image 283
PegasusFantasy Avatar asked Apr 23 '17 17:04

PegasusFantasy


People also ask

How do you match an integer in regex?

1.5 Example: Positive Integer Literals [1-9][0-9]*|0 or [1-9]\d*|0. [1-9] matches any character between 1 to 9; [0-9]* matches zero or more digits. The * is an occurrence indicator representing zero or more occurrences. Together, [1-9][0-9]* matches any numbers without a leading zero.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

Does regex work with integers?

Matches any integer number or numeric string, including positive and negative value characters (+ or -).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

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

like image 142
Rahul Avatar answered Sep 24 '22 01:09

Rahul


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

like image 45
pradosh nair Avatar answered Sep 25 '22 01:09

pradosh nair