簡體   English   中英

Bash正則表達式匹配不起作用 - 轉義所有特殊字符

[英]Bash regex match not working - escaping all special characters

我遇到了與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

不對[[和]]之間的單詞執行單詞拆分和路徑名擴展; 執行波形擴展,參數和變量擴展,算術擴展,命令替換,進程替換和引用刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM