Regex - validate IPv6 shell script

2019-08-27 04:51发布

问题:

I am able to validate IPv6 addresses using java with following regex:

([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}

But I need to do this in shell script to which I am new.

This regex doesn't seem to work in shell. Have tried some other combinations also but nothing helped.

#!/bin/bash
regex="([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}"
var="$1"

if [[ "$var" =~ "$regex" ]]
then
        echo "matches"
else
        echo "doesn't match!"
fi

It gives output doesn't match! for 2001:0Db8:85a3:0000:0000:8a2e:0370:7334

How can I write this in shell script?

回答1:

Java regex shown in question would work in bash as well but make sure to not to use quoted regex variable. If the variable or string on the right hand side of =~ operator is quoted, then it is treated as a string literal instead of regex.

I also recommend using anchors in regex. Otherwise it will print matches for invalid input as: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:foo:bar:baz.

Following script should work for you:

#!/bin/bash

regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'
var="$1"

if [[ $var =~ $regex ]]; then
    echo "matches"
else
    echo "doesn't match!"
fi


标签: regex bash shell