Bash中的正则表达式"如果"声明

时间:2018-03-04 19:40:05

标签: regex bash

if [[ $1  =~ ^\'*\"*[\d+\w+]+\'*\"*$ ]]
    then
        echo true
    else
        echo error
        exit 1
fi

此正则表达式似乎是正确的(使用https://regexr.com和其他正则表达式网站验证),但是,该脚本将评估为false。 知道为什么吗?

对于这个论点,我期待一个如下的行:

Will0w

然而,要匹配,没有运气。

任何帮助将不胜感激,

由于

2 个答案:

答案 0 :(得分:2)

使用

# The !! operator is a handy syntactic shortcut for unquoting with
# UQ().  However you need to be a bit careful with operator
# precedence. All arithmetic and comparison operators bind more
# tightly than `!`:
quo(1 +  !! (1 + 2 + 3) + 10)

# For this reason you should always wrap the unquoted expression
# with parentheses when operators are involved:
quo(1 + (!! 1 + 2 + 3) + 10)

# Or you can use the explicit unquote function:
quo(1 + UQ(1 + 2 + 3) + 10)

答案 1 :(得分:1)

使用grep的替代解决方案:

if echo $1 | grep -qP "^\'*\"*[\d+\w+]+\'*\"*$"
    then
        echo true
    else
        echo error
        exit 1
fi