逃脱字符``在括号表达式中



我读了一个示例,该示例摘自指令,
并打算在^[-[:alnum:]._]+$

中检查
# is input a valid filename?
read -p "Enter a single item > "
if [[ "$REPLY" =~ ^[-[:alnum:]._]+$ ]]; then
    echo "'$REPLY' is a valid filename."
else
    echo "The string '$REPLY' is not a valid filename."
fi

通过喂食一些组合来检查括号表达式。

$ bash read_validate.sh
Enter a single item > test.tst.
'test.tst.' is a valid filename.'
#test ``
$ bash read_validate.sh
Enter a single item > test\tst
The string 'testtst' is not a valid filename.

当我从^[-[:alnum:]._]+$中删除逃生时,为 ^[-[:alnum:]._]+$

$ bash read_validate.sh
Enter a single item > test.tst
'test.tst' is a valid filename.
# to assert that dot is not the any character sign.
$ bash read_validate.sh
Enter a single item > test*tst
The string 'test*tst' is not a valid filename.
# codes run properly.

似乎没有必要将逃生插入模式。

是吗?
我无法确定是否省略了有关括号表达式和逃脱字符的一些关键点?

bash使用扩展的正则表达式。引用标准:

特殊字符'。','*','['和'(时期,星号,左支架和后斜线(在括号表达式中应失去其特殊含义。

所以在[ ]中,它们不需要逃脱。

由于bash过程在您的字符串中进行后斜切的事实使情况变得更加复杂:

$ set -x
$ [[ '' =~ [.] ]] && echo yes
+ [[  =~ [.] ]]                # look, no backslash!

因此,使用正则表达式的推荐方法是设置一个外壳变量:

$ re='[.]'
+ re='[.]'
$ [[ '' =~ $re ]] && echo yes
+ [[  =~ [.] ]]               # backslash preserved!
+ echo yes
yes    

最新更新