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
复制代码

 。

 

posted @   小鲨鱼2018  阅读(1633)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!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中函数形式参数、实际参数、位置参数、关键字参数
点击右上角即可分享
微信分享提示