Regex for positive or negative integer only with no look arounds

Viewed 42

I would like to match integers only. No decimals and no leading 0s. Look arounds are not allowed. The best solution I had was ^\d+$ but it matches 0001 on https://regex101.com/.

Here are some test cases

1 
-1 
+1 
A1
)1 
0.1 
0001
1,000
1.1
0

This is what the result must be

1 #true
-1 #true
+1 #true
A1 #false
)1 #false
0.1 #false
0001 #false
1,000 #false
1.1 #false
0 #true

Edit

I also added the condition to match 0.

1 Answers

You can use

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

See the regex demo and the regex graph:

enter image description here

Details:

  • ^ - start of string
  • ( - start of a group:
    • [+-]? - a - or +, optional
    • [1-9] - a digit from 1 to 9
    • [0-9]* - any zero or more digits
  • | - or
    • 0 - a zero
  • $ - end of string.
Related