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:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |