【问题标题】:Bash regex match not working - escaping all special characters [duplicate]Bash正则表达式匹配不起作用-转义所有特殊字符[重复]
【发布时间】:2014-04-22 16:49:01
【问题描述】:

我遇到了 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\\\) ]]

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

【问题讨论】:

    标签: regex bash


    【解决方案1】:

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

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

    在双方括号中,不需要引用变量,因为它们是以特殊方式解析的。详情见man bash

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-25
    • 2011-08-21
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多