tso
tso

Reputation: 307

Grep: Regex for IP doesnt match

I was trying to create a regex that match a ip adress, or a ip adress with netmask: something like 8.8.8.8/24

if ! [[ $SOURCE =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || [[ $SOURCE =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}$ ]];then
                echo ERROR: Invalid Source
                exit 1
fi

The first part matchted well, the second, with the netmask doest match.. Anyone know why?

Upvotes: 1

Views: 193

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

Define the regexps in separate variables and use a single pattern:

SOURCE="8.8.8.8"
RX="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2})?$"
if ! [[ $SOURCE =~ $RX ]];then
                echo ERROR: Invalid Source
                exit 1
fi

See the online demo here.

Pattern explanation:

  • ^ - start of string
  • [0-9]{1,3}\. - 1 to 3 digits followed with a literal dot
  • [0-9]{1,3}\.[0-9]{1,3}\. - same as above, 2 times
  • [0-9]{1,3} - 1 to 3 digits (this matches the IP string)
  • (/[0-9]{1,2})? - an optional (1 or 0 occurrences) sequence of:
    • / - a slash (since it is not a special char, it needs no escaping)
    • [0-9]{1,2} - 1 to 2 digits
  • $ - end of string.

Upvotes: 1

Related Questions