Regex for number or specific number

Viewed 51

I am unable to create a regex expression for below condition.

 var1 = '123'
 var2 = '-999'
 var3 = '$##99$#%'
 var4 = '-9999'
 var5 = '-123'
 var6 = '-99'`

Conditions:

  • accept all integers with max length of 10 digits.
  • not accept any characters or symbols.
  • accept only '-999' value apart first point(only three digits).
  • not accept any integers starting with '-' and other than '999'.

var1 and var2 are valid, the rest three are not valid.

This is what I tried so far:

^[-]?[0-9]{4}$

/^\d{1,10}?$/

1 Answers

Just check from the beginning of the string for 1 to 10 digits OR exactly -999:

^(\d{1,10}|-999)$
  • ^ start of string
  • ( group
  • \d{1,10} 1 to 10 digits
  • | OR
  • exactly -999
  • ) end group
  • $ end of string

Here's a place to check it: https://regex101.com/r/iMippW/1

Related