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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityThe 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?
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)
-x
grep
option to anchor the regexp at start and end.
Feb 8, 2018 at 15:57
Most programs that use regex patterns actually implement a search of the pattern, instead of a full-string match. Python has distinct search()
and match()
methods where search()
matches anywhere in the string, and match()
only at the beginning. grep
has the -x
option to demand a match against the whole string; by default it matches anywhere in the string. Others, like sed
, awk
and Perl will happily look for the pattern anywhere in the string. Use the ^
and $
modifiers ("anchors") to force the pattern to the start or end of the string (respectively).
So, the ERE pattern you want is probably this:
^-?[1-9]?[0-9]$
expr
that anchors at the start but not at the end (uses BREs though, not those EREs).
Feb 8, 2018 at 16:17