0

Sorry if this was asked before but I cant find a solution, except for Windows and regex. Both I am not familiar with.

I would like to validate a network-address like 192.168.1.0/24, or an IP like 192.168.1.1 .

This is what I came up with ...

if [[ "$1" =~ ^[1-255].[0-255].[0-255].0/[8-32]$ ]]; then
    echo "Parameter: network-address is missing."
fi

But this if-test doesn't work at all. The exclamation mark is also missing.

Any solutions ?

Mario
  • 679
  • 6
  • 10
  • `[1-255]` is a character class that matches the single character `1`, the single character `2`, or the single character `5`. Regular expression syntax does not have any way to match a multi-digit string if and only if it has a decimal value within a specific range. – Charles Duffy Apr 26 '18 at 21:49
  • 1
    Matching anything from 1-255 might look more like `([[:digit:]]{1,2}|1[[:digit:]]{2}|2[0-4][0-9]|25[0-5])` -- which is to say that as the regex's author, it's your job to match the strings for all the numbers in the range. – Charles Duffy Apr 26 '18 at 21:51
  • ...note that while the linked duplicate uses grep, there's no reason you can't use `=~` for this purpose so long as your regex is built appropriately (as that question and its answers discuss). Take out the `\b`s and other extensions, f/e. – Charles Duffy Apr 26 '18 at 21:52
  • thanks for the clarification. I will try what you said. – Mario Apr 26 '18 at 21:58
  • (Also note that a literal dot should be matched with `[.]` -- otherwise it's a wildcard in regex syntax. Some folks also use `\.`, but that's less consistent in terms of how it behaves across different quoting contexts). – Charles Duffy Apr 26 '18 at 22:00

0 Answers0