Bash正则表达式匹配不起作用-转义所有特殊字符 [英] Bash regex match not working - escaping all special characters

查看:142
本文介绍了Bash正则表达式匹配不起作用-转义所有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash正则表达式匹配方面遇到问题.我有这样的正则表达式:

I'm having problem with bash regex match. I have regex like this:

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脚本时的某种原因,我可以看到它与这里的字符串不匹配:

For me everything here looks good for now but for some reason while debugging bash script I can see that it doesn't match string here:

+ [[ 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\\\) ]]

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

For some reason regex pattern is escaped.

推荐答案

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

Remove the double quotes from the regular expression in the match:

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

在双方括号中,无需引用变量,因为它们以特殊方式进行了解析.有关详情,请参见man bash:

In double square brackets, there is no need to quote variables, as they are parsed in a special way. See man bash for details:

[[和]]之间的单词不执行单词拆分和路径名扩展;执行波浪号扩展,参数和变量扩展,算术扩展,命令替换,进程替换和引号删除.

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.

这篇关于Bash正则表达式匹配不起作用-转义所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆