我正在嘗試使用 regext 來檢測字串是否以特定模式開頭,但它對我不起作用:
#!/bin/bash
line="{{ - hello dear - }}"
if [[ "${line}" =~ ^\{\{\s*-\s*hello\s*.*\}\} ]]; then
echo "got it "
fi
在這個例子中,我希望 if 條件檢測到行變數有一個以“{{ - hello”開頭并以“}}”結尾的字串但是,它沒有這樣做,因為沒有列印回顯訊息!
uj5u.com熱心網友回復:
您可以將正則運算式存盤在變數中以使其作業。這是 3.2 中的解決方法。不知道為什么在新版本中再次需要它。
#!/bin/bash
line="{{ - hello dear - }}"
regex='^\{\{\s*-\s*hello\s*.*\}\}'
if [[ "${line}" =~ $regex ]]; then
echo "got it "
fi
還可以考慮使用擴展模式匹配 with==代替。我相信它的“引擎”較弱,但有時更具可讀性。
shopt -s extglob
...
[[ $line == "{{ - hello dear - }}"* ]] && echo "Got it."
(實際上,這甚至還不是擴展模式。)
uj5u.com熱心網友回復:
這里沒有真正需要使用正則運算式。您可以bash像這樣使用 glob 匹配:
line="{{ - hello dear - }}"
[[ $line == '{{ - hello'*'}}' ]] && echo "got it "
got it
uj5u.com熱心網友回復:
問題是\s,但您可以用 POSIX 組替換它們中的每一個[[:space:]]:
#!/bin/bash
line='{{ - hello dear - }}'
[[ $line =~ ^\{\{[[:space:]]*-[[:space:]]*hello[[:space:]]*.*[[:space:]]*.*[[:space:]]*\}\}.* ]] && echo 'got it '
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/404404.html
標籤:
