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.
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.
$ 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.
Matches any integer number or numeric string, including positive and negative value characters (+ or -).
[] 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 .
You should be using alteration to define two categories of numbers.
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
This should do the trick. [0]*([2-9]+|[1-9][0-9][0-9]*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With