正则表达式-验证IPv6 Shell脚本 [英] Regex - validate IPv6 shell script

查看:132
本文介绍了正则表达式-验证IPv6 Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用带有以下正则表达式的java来验证IPv6地址:

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

但是我需要在我刚接触的shell脚本中执行此操作.

此正则表达式在shell中似乎不起作用.也尝试过其他组合,但无济于事.

 #!/bin/bashregex =([[0-9a-fA-F] {0,4}:){1,7}([0-9a-fA-F]){0,4}"var ="$ 1"如果[["$ var" =〜"$ regex"]]然后回声匹配"别的回声不匹配!"科幻 

对于 2001:0Db8:85a3:0000:0000:8a2e:0370:7334 ,它给出的输出不匹配!

如何用Shell脚本编写此代码?

解决方案

有问题的Java正则表达式也可以在bash中运行,但请确保不要使用带引号的正则表达式变量.如果用 =〜运算符右侧的变量或字符串加引号,则将其视为字符串文字而不是正则表达式.

我还建议在正则表达式中使用锚.否则,它将打印无效输入的匹配项,例如: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:foo:bar:baz .

以下脚本应该对您有用:

 #!/bin/bashregex ='^([0-9a-fA-F] {0,4}:){1,7} [0-9a-fA-F] {0,4} $'var ="$ 1"如果[[$ var =〜$ regex]];然后回声匹配"别的回声不匹配!"科幻 

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?

解决方案

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

这篇关于正则表达式-验证IPv6 Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆