检查字符串是否与 Bash 脚本中的正则表达式匹配 [英] Check if a string matches a regex in Bash script
问题描述
我的脚本接收的参数之一是以下格式的日期:yyyymmdd
.
我想检查输入的日期是否有效.
我该怎么做?我正在尝试使用如下正则表达式: [0-9]{8}
您可以使用测试结构 [[ ]]
以及正则表达式匹配运算符 =~
,检查字符串是否与正则表达式匹配.
对于你的具体情况,你可以写:
[[ $date =~ ^[0-9]{8}$ ]] &&回声是"
或者更准确的测试:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] &&回声是"# |\______/\______*______/\______*__________*______/|# |||||# |||||# |--年-- --月-- --日-- |# |要么 01...09 要么 01..09 |# 行首或 10,11,12 或 10..29 |# 或 30, 31 |# 行结束
也就是说,您可以在 Bash 中定义一个与您想要的格式匹配的正则表达式.你可以这样做:
[[ $date =~ ^regex$ ]] &&回声匹配"||回声不匹配"
where &&
之后的命令如果测试成功就执行,||
之后的命令如果测试不成功就执行.
请注意,这是基于 Aleks-Daniel Jakimenko 在 bash 中的用户输入日期格式验证中的解决方案.>
在其他 shell 中,您可以使用 grep.如果您的 shell 符合 POSIX,请执行
(echo "$date" | grep -Eq ^regex$) &&回声匹配"||回声不匹配"
在不符合 POSIX 的 fish 中,您可以这样做
echo "$date";|grep -Eq "^regex$";并回显匹配";或回声不匹配"
One of the arguments that my script receives is a date in the following format: yyyymmdd
.
I want to check if I get a valid date as an input.
How can I do this? I am trying to use a regex like: [0-9]{8}
You can use the test construct, [[ ]]
, along with the regular expression match operator, =~
, to check if a string matches a regex pattern.
For your specific case, you can write:
[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
Or more a accurate test:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |\______/\______*______/\______*__________*______/|
# | | | | |
# | | | | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 |
# start of line or 10,11,12 or 10..29 |
# or 30, 31 |
# end of line
That is, you can define a regex in Bash matching the format you want. This way you can do:
[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
where commands after &&
are executed if the test is successful, and commands after ||
are executed if the test is unsuccessful.
Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
In other shells you can use grep. If your shell is POSIX compliant, do
(echo "$date" | grep -Eq ^regex$) && echo "matched" || echo "did not match"
In fish, which is not POSIX-compliant, you can do
echo "$date" | grep -Eq "^regex$"; and echo "matched"; or echo "did not match"
这篇关于检查字符串是否与 Bash 脚本中的正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!