0

In bash script, /d fails while same worked with [0-9]

ip="106.990.120.78"

regex1="^(\d+\.){3}\d+$"
regex2="^([0-9]+\.){3}[0-9]+$"

if [[ $ip =~ $regex2 ]]; then
  echo "success"
else
  echo "fail"
fi

Both patterns work same in https://regex101.com/r/cNhDAL/1

/d also used for numeric that are in string. Why such behavior in bash shell?

Note: I am just matching the pattern only, not checking either IP is valid or not

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
  • 1
    There are multiple implementations of regex, the one you're using doesn't parse `\d` as the numerics class' shorthand notation. More info [here](https://www.regular-expressions.info/posix.html) on the two regex flavours defined by POSIX – Aaron Mar 27 '21 at 18:52
  • 2
    See [this answer](https://stackoverflow.com/a/48898886/10248678). – oguz ismail Mar 27 '21 at 18:53
  • 1
    `d=[[:digit:]]` and than do: `regex1="^($d{1,3}\.){3}$d{1,3}$"` – Roko C. Buljan Mar 27 '21 at 18:58
  • @RokoC.Buljan Thanks its also worthful. Does this way only work in bash or can work in other langs also? – dahiya_boy Mar 27 '21 at 19:03
  • 1
    If you use zsh instead of bash, you can get support for pcre dialect regular expressions, btw. – Shawn Mar 27 '21 at 19:04
  • @dahiya_boy will not work in other languages. I.E: in JavaScript `[[:digit:]]` is invalid syntax. – Roko C. Buljan Mar 27 '21 at 19:05
  • @Shawn Thanks for info, I not aware of such limitations, i will not for future. – dahiya_boy Mar 27 '21 at 19:05
  • Shawn oguzismail Aaron RokoC.Buljan thanks for sharing knowledge. – dahiya_boy Mar 27 '21 at 19:07
  • 1
    you could always create a replacer: wherever you detect a `\d` (and if it's not preceded by ` \ \`) and if the ENV is bash - replace it with `[[:digit:]]` etc etc for the other special references. – Roko C. Buljan Mar 27 '21 at 19:07
  • @RokoC.Buljan a/c to answer shared by oguz there are many chars that are not supported by bash, Is there any blog that specifies the replacement in bash so that I can refer from there. – dahiya_boy Mar 27 '21 at 19:09
  • 1
    @dahiya_boy `\d \D \s \S \w \W` https://stackoverflow.com/a/48898886/383904 – Roko C. Buljan Mar 27 '21 at 19:12

0 Answers0