1

I am new to regeX and I am looking for a expression which satisfy the below condition

  1. should validate numbers only. decimal is not accepted.(eg :123, 11, 1025,0548)
  2. should not greater than 7 digits

I tried the below regeX

^[1-9][0-9]*$

but it works fine for numbers which greater than 0.

and then I tried

 ^[1-9][0-9]\d{1,7}$

but it accept if the digits is greater than 2 numbers. when I give 12 it returns false. when I give 123 it returns true

and when I give 0124 this will also return false

please refer the below points also for different inputs

  1. 1, 12, 432, 12414, 1234567 etc all are valid inputs. its greater than 0 and max length is 7
  2. 01, 0121, 0000001 etc are also valid. 0000001 is greater than 0.
  3. 0, 12345678 etc are invalid, because it should not accept less than 0 or length greater than 7
  4. all negative values are invalid, all characters are invalid
ruohola
  • 21,987
  • 6
  • 62
  • 97
Sandeep Sudhakaran
  • 1,072
  • 2
  • 9
  • 22

2 Answers2

1

You can use negative lookahead for this. This pattern will work fine:

^(?!0+$)\d{1,7}$

Explanation:

  • ^(?!0+$) negative lookahead, which checks that the string is not all 0s. A negative lookahead means, that if this matches, the whole pattern will not match.
  • ^ \d{1,7}$ checks that the string consists of 1 to 7 characters, which all are numbers.

(I'm reusing the ^ anchor for both the lookahead and the actual pattern, because they can share it, since the lookahead is at the start. The ^ could also be added to the lookahead: (?!^0+$), but it wouldn't affect anything.)

regex101 demo

ruohola
  • 21,987
  • 6
  • 62
  • 97
1

You could us a positive lookahead (?=[0-9]*[1-9]) if supported to assert at least a digit 1-9 and then match 1- 7 digits.

^(?=[0-9]*[1-9])[0-9]{1,7}$

In parts

  • ^ Start of string
  • (?= Positive lookahead, assert what is on the right is
    • [0-9]*[1-9] Match 0+ times a digit 0-9, then a digit 1-9
  • ) Close lookahead
  • [0-9]{1,7} Match a digit 0-9 1-7 times
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70