如何在 Bash 中使用 =~ 操作符 ?
在 Bash 脚本世界中,有各种操作符可供我们使用,使我们能够操作、比较和测试数据。其中一个操作符是 =~ 操作符。这个操作符经常被忽视,但功能非常强大,它为我们提供了一种使用正则表达式匹配字符串模式的方法。
=~ 操作符语法
语法很简单,=~ 操作符在 [[ ]] 中使用,字符串和正则表达式是操作数,如下所示
[[ string =~ regular_expression ]]
如果字符串匹配模式,操作符返回 0 (true),如果不匹配,则返回 1 (false)
Example 1: 简单模式匹配
让我们从一个基本的例子开始。有一个字符串 “Welcome to Bash scripting”,我们想看看这个字符串是否包含“Bash” 这个词。
#!/bin/bashstr="Welcome to Bash scripting"if [[ $str =~ Bash ]]; thenecho "The string contains the word Bash."
elseecho "The string does not contain the word Bash."
fi
Example 2: 正则表达式匹配
=~ 操作符允许正则表达式模式匹配。假设我们想要检查一个字符串是否包含数字。
#!/bin/bashstr="Order 5 pizzas"if [[ $str =~ [0-9]+ ]]; thenecho "The string contains a digit."
elseecho "The string does not contain a digit."
fi
Example 3: 提取正则匹配
=~ 操作符也可用于提取匹配项。假设有一个日期字符串,我们想提取 day 、month 和 year
#!/bin/bashdate="23-05-2023"
regex="([0-9]{2})-([0-9]{2})-([0-9]{4})"if [[ $date =~ $regex ]]; thenday=${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仓库)