Home > Back-end >  Regex - numeric only with negatives allowed, but only one leading zero
Regex - numeric only with negatives allowed, but only one leading zero

Time:02-04

I'm struggling to find a way to allow numeric only numbers that can also be negative, but also allow only one leading zero.
Goal Examples: 0, 12345, -555 Bad Examples: -0, 01235, -012

I have the following so far, but cant seem to work in the negative character properly. If I type - first nothing can be typed afterwards, but it should allow 1-9: /^([-0]|[1-9]\d*)$/

Tried this as well, but no luck: /^[-]?(0|[1-9]\d*)$/

Any help would be greatly appreciated.

CodePudding user response:

Let's keep it simple:

/^(?:0|-?[1-9][0-9]*)$/

Explanation:

^       # Start of string
(?:     # Start of non-capturing group
 0      # Match either a zero (and nothing else)
|       # or
 -?     # an optional -
 [1-9]  # a digit between 1 and 9
 [0-9]* # 0 or more further digits
)       # End of group
$       # End of string

CodePudding user response:

Try the following: (see here)

\b0\b|-?\b(?!^0)[1-9] [0-9]*\b
  • Related