Bash =~ regex and https://regex101.com/
\d
is a nonstandard way for saying "any digit". I think it comes from Perl, and a lot of other languages and utilities support Perl-compatible REs (PCRE), too. (and e.g. GNU grep 2.27 in Debian stretch supports the similar \w
for word characters even in normal mode.)
Bash doesn't support \d
, though, so you need to explicitly use [0-9]
or [[:digit:]]
. Same for the non-capturing group (?:..)
, use just (..)
instead.
This should print match
:
temp="eu-west 140.243.64.99 "
regexp="([0-9]{1,3}\.)+([0-9]{1,3})"
[[ $temp =~ $regexp ]] && echo match
(:...)
and \d
are perl or PCRE regular expression operators (like in GNU grep -P
).
bash
only supports extended regular expressions as in grep -E
except that for regexps passed literally as in [[ text =~ regexp-here ]]
as opposed to as the result of an unquoted expansion (as in [[ text =~ $var ]]
or [[ test =~ $(printf '%s\n' 'regexp-here') ]]
), it's limited to the POSIX extended regular expression feature set.
So even on systems where the grep -E '\d'
would work (GNU EREs have already imported some extensions from perl regexps like \s
so future versions might have \d
as well), you'd have to use:
regexp='\d'
[[ $text =~ $regexp ]]
in bash
for it to work ([[ $text =~ \d ]]
wouldn't).
For a shell that supports PCREs, you may want to use zsh
instead:
set -o rematchpcre
[[ $text =~ '(?:\d{1,3}\.)+(?:\d{1,3})' ]]
ksh93 also supports its own implementation of perl-like regular expressions (not fully compatible) as part of its pattern matching. There, you'd use:
regexp='~(P)(?:\d{1,3}\.)+(?:\d{1,3})'
[[ $text = $regexp ]]
(note the =
instead of =~
. You'll want to use temporary variables as the it is very buggy when you don't)