Why is this number matched with this regex

regular expression

The regex is -?([0-9]|([1-9][0-9])).

The number is -2231 and it's being matched. From my understanding, it should be a single digit or double digits. 
Why is this number matched with this regex?

Best Answer

The regular expression is not anchored, so it's free to match the first 1 or two numbers and "succeed", leaving the trailing numbers (successfully) unmatched.

If you require 1 or 2 digit numbers, anchor the regex:

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

Some examples:

$ seq -100 -99 | grep -E '^-?([0-9]|[1-9][0-9])$'
-99

$ seq 99 100 | grep -E '^-?([0-9]|[1-9][0-9])$'
99

$ seq -9 9  | grep -E '^-?([0-9]|[1-9][0-9])$'
-9
-8
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
4
5
6
7
8
9

$ seq -2231 -100 | grep -E '^-?([0-9]|[1-9][0-9])$'
(empty)
Related Question