加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash正则表达式匹配不起作用 – 转义所有特殊字符

发布时间:2020-12-15 21:34:22 所属栏目:安全 来源:网络整理
导读:我遇到了与bash正则表达式匹配的问题.我有这样的正则表达式: re="fatal: file not found: .+/tmp_dir_1234/([^ ]*) (No such file or directory)"test="fatal: file not found: /some/path/irrelevant/something/tmp_dir_1234/somefile.txt (No such fil
我遇到了与bash正则表达式匹配的问题.我有这样的正则表达式:

re="fatal: file not found: .+/tmp_dir_1234/([^ ]*) (No such file or directory)"
test="fatal: file not found: /some/path/irrelevant/something/tmp_dir_1234/somefile.txt (No such file or directory)"
if [[ "$test" =~ "$re" ]]; then
    echo "match!"
fi

对我来说,这里的一切看起来都不错,但出于某种原因,在调试bash脚本时我可以看到它与字符串不匹配:

+ [[ fatal: file not found: /some/path/irrelevant/something/tmp_dir_1234/somefile.txt (No such file or directory) =~ fatal: file not found: .+/tmp_dir_1234/([^ ]*) (No such file or directory) ]]

出于某种原因,正则表达式模式被转义.

解决方法

从匹配中的正则表达式中删除双引号:

if [[ "$test" =~ $re ]]; then
    echo "match!"
fi

在双方括号中,不需要引用变量,因为它们是以特殊方式解析的.有关详细信息,请参阅man bash:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion,parameter and variable expansion,arithmetic expansion,command substitution,process substitution,and quote removal are performed.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读