如何檢查給定字符串是否以http
/https
開頭並以jpg
/jpeg
結尾?
換句話說,我要驗證以下內容:jpg
jpeg
JPG
`JPEG
我嘗試:
http
或
https
- 字符串開頭
if [[ $1 = http?(s)://*.jpg ]]; then echo "invalid URL" fi
如何檢查給定字符串是否以http
/https
開頭並以jpg
/jpeg
結尾?
換句話說,我要驗證以下內容:jpg
jpeg
JPG
`JPEG
我嘗試:
http
或
https
if [[ $1 = http?(s)://*.jpg ]]; then
echo "invalid URL"
fi
您可以使用此BASH正則表達式:
[[ ${1,,} =~ ^https?://.+\.jpe?g$ ]]
${1,,}
是$1
轉換爲全部小寫$1
有http://
或https://
在啓動,並將其與jpg
或jpeg
你在正確的軌道上。您可以設置nocasematch
選項使其不區分大小寫,並且您只需要在擴展中添加可選e
,方法與檢查協議中的可選s
的方式相同。
shopt -s nocasematch
shopt -s extglob # may not be necessary
if [[ $1 = http?(s)://*.jp?(e)g ]];
then
echo "invalid URL"
fi
舊版本的bash
可能需要您打開擴展模式匹配與shopt -s extglob
裏面使用[[
的?(...)
模式;新版本將[[ ... ]]
中的模式自動視爲擴展模式。
非常感謝你,工作得很好。我怎樣才能讓它檢查JPG和JPEG也是一個關鍵敏感? –
檢查我更新的答案。 – anubhava