Regex 这个正则表达式的变量赋值有什么问题
简单的正则表达式,用于检查输入的字符串是否匹配为IP地址。如果将正则表达式直接与参数进行比较,则效果良好,但如果我对正则表达式使用变量赋值,则效果不佳 我已经用一些不同的语法进行了测试,但是仍然不起作用,除非我直接使用正则表达式Regex 这个正则表达式的变量赋值有什么问题,regex,bash,sh,Regex,Bash,Sh,简单的正则表达式,用于检查输入的字符串是否匹配为IP地址。如果将正则表达式直接与参数进行比较,则效果良好,但如果我对正则表达式使用变量赋值,则效果不佳 我已经用一些不同的语法进行了测试,但是仍然不起作用,除非我直接使用正则表达式 #!/bin/bash #provide one word/sentence as an argument to the script. If in that sentence will be ip address, #find out, if that ip add
#!/bin/bash
#provide one word/sentence as an argument to the script. If in that sentence will be ip address,
#find out, if that ip address is reachable or not.
#argument check
if [ $# -ne 1 ]; then
echo "Provide exactly one argument e.g. $0 argument"
exit 1
fi
var1=$1
#ip address regex 127.0.0.1
regexp="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1-3}\.[0-9]{1,3}"
#regex check
#if ! [[ $var1 =~ [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} ]]; then
if ! [[ $var1 =~ $regexp ]]; then
echo "No IP address provided"
exit 2
fi
IP=${BASH_REMATCH[0]}
#find if ip address is reachable or not
ping -c4 $IP
if [ $? -eq 0 ]; then
status="Alive"
else
status="Dead"
fi
echo "IP found: $IP ($status)"
与:
它可以正常工作,但不能用于:
regexp="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1-3}\.[0-9]{1,3}"
我研究了很多文章,但没有找到一个明确的答案
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1-3}\.[0-9]{1,3}
# ^
应该是
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
# ^
[0-9]{1,3}\[0-9]{1,3}\[0-9]{1-3}\[0-9]{1,3}
!=<代码>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}注意返回代码是2
,这表明正则表达式在语法上是无效的。天哪,感谢你指出了这一点,不知怎的,我在多次阅读之后错过了这一部分。非常感谢,为这个新手的错误感到抱歉
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1-3}\.[0-9]{1,3}
# ^
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
# ^