在 Bash 腳本世界中,有各種操作符可供我們使用,使我們能夠操作、比較和測試數據。其中一個操作符是 =~ 操作符。這個操作符經常被忽視,但功能非常強大,它為我們提供了一種使用正則表達式匹配字符串模式的方法。
=~ 操作符語法
語法很簡單,=~ 操作符在 [[ ]] 中使用,字符串和正則表達式是操作數,如下所示
[[ string =~ regular_expression ]]
如果字符串匹配模式,操作符返回 0 (true),如果不匹配,則返回 1 (false)
Example 1: 簡單模式匹配
讓我們從一個基本的例子開始。有一個字符串 “Welcome to Bash scripting”,我們想看看這個字符串是否包含“Bash” 這個詞。
#!/bin/bash
str="Welcome to Bash scripting"
if [[ $str =~ Bash ]]; then
echo "The string contains the word Bash."
else
echo "The string does not contain the word Bash."
fi
Example 2: 正則表達式匹配
=~ 操作符允許正則表達式模式匹配。假設我們想要檢查一個字符串是否包含數字。
#!/bin/bash
str="Order 5 pizzas"
if [[ $str =~ [0-9]+ ]]; then
echo "The string contains a digit."
else
echo "The string does not contain a digit."
fi
Example 3: 提取正則匹配
=~ 操作符也可用於提取匹配項。假設有一個日期字符串,我們想提取 day 、month 和 year
#!/bin/bash
date="23-05-2023"
regex="([0-9]{2})-([0-9]{2})-([0-9]{4})"
if [[ $date =~ $regex ]]; then
day=${BASH_REMATCH[1]}
month=${BASH_REMATCH[2]}
year=${BASH_REMATCH[3]}
echo "Day: $day, Month: $month, Year: $year"
fi
我的開源項目
- course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
- course-tencent-cloud(酷瓜雲課堂 - github倉庫)