linux shell脚本中 =~ 的作用
linux shell脚本中 =~ 的作用
=~ 表示正则表达式左侧是否匹配右侧。
001、举例如下:
[root@pc1 test1]# str1=12343 ## 纯数字字符串 [root@pc1 test1]# str2=abdef ## 字母字符串 [root@pc1 test1]# str3=132ds ## 数字加字母字符串 [root@pc1 test1]# [[ $str1 =~ [0-9]+ ]] [root@pc1 test1]# echo $? ## 纯数字,返回0 0 [root@pc1 test1]# [[ $str2 =~ [0-9]+ ]] ## 纯字母,返回1 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str3 =~ [0-9]+ ]] ## 匹配至少1个数字,返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ [0-9]+$ ]] ## 必须全部是数字,返回1 [root@pc1 test1]# echo $? 1
002、测试2
[root@pc1 test1]# str1=12343 [root@pc1 test1]# str2=abdef [root@pc1 test1]# str3=132ds [root@pc1 test1]# [[ $str1 =~ [a-z]+$ ]] ## 匹配字母一直到最后,匹配失败,返回1 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str2 =~ [a-z]+$ ]] ## 匹配成功,返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ [a-z]+$ ]] ## 匹配成功, 返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ ^[a-z]+$ ]] ## 匹配失败, 返回1 [root@pc1 test1]# echo $? 1
。
003、测试3
[root@pc1 test1]# str1=12343 [root@pc1 test1]# str2=abdef [root@pc1 test1]# str3=132ds [root@pc1 test1]# [[ $str1 =~ [a-Z]+[0-9]+ || $str1 =~ [0-9]+[a-z]+ ]] ## str为出数字 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str2 =~ [a-Z]+[0-9]+ || $str2 =~ [0-9]+[a-z]+ ]] ## str2为纯字母 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str3 =~ [a-Z]+[0-9]+ || $str3 =~ [0-9]+[a-z]+ ]] ## str3为数字加字母 [root@pc1 test1]# echo $? 0
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-03-04 python中的内嵌函数
2021-03-04 python中函数的闭包
2021-03-04 python中的内嵌函数
2021-03-04 python中函数的global关键字
2021-03-04 python中函数的局部变量
2021-03-04 python中函数的收集参数
2021-03-04 python中函数形式参数、实际参数、位置参数、关键字参数