Shell编程--正则表达式(基本/拓展元字符、正则判断)

正则表达式

  • 1.基本元字符
  • 2.拓展元字符
  • 3.正则判断=~

1.基本元字符

字符 功能 示例
^ 行首定位符 ^love
$ 行尾定位符 love$
. 匹配单个字符 l…e
* 匹配前导符0到多次 ab*love
.* 匹配任意多个字符(贪婪匹配) ab.*love
[] 匹配方括号中任意一个字符 [lL]ove
[-] 匹配指定范围内的一个字符 [a-zA-Z0-9]ove
[^] 匹配不在指定组里的字符 [^a-z0-9]ove
\ 用来转义元字符 love\.
\< 词首定位符 \
\> 词尾定位符 love>\

练习:

[root@localhost ~]# cat test.txt
Love
love
loveyou
aaabbblove
a123love
www.love.com
i love you
do you love me

//以lo开头
[root@localhost ~]# grep  ^lo test.txt 
love
loveyou
[root@localhost ~]# grep -i ^lo test.txt    //-i不区分大小写
Love
love
loveyou

//以me结尾
[root@localhost ~]# grep  me$ test.txt
do you love me

//匹配单个字符,一个.代表一个字符
[root@localhost ~]# grep  y.u test.txt
loveyou
i love you
do you love me
[root@localhost ~]# grep  l.e test.txt
[root@localhost ~]# grep  l..e test.txt
love
loveyou
aaabbblove
a123love
www.love.com
i love you
do you love me

//匹配前导符0到多次;前导符是"a" 即*前面a有0次到多次
[root@localhost ~]# grep a*l test.txt
love
loveyou
aaabbblove
a123love
www.love.com
i love you
do you love me

//贪婪匹配;匹配任意多个字符;即*的前导符是"a." 但是"."可以匹配任意单个字符
[root@localhost ~]# grep a.*l test.txt
aaabbblove
a123love

//匹配中括号中任意一个字符
[root@localhost ~]# grep a[0-9]l*  test.txt
a123love

//匹配指定范围内的一个字符
[root@localhost ~]# grep a[0-9a-z]l*  test.txt
aaabbblove
a123love

//匹配不在指定组里的字符
[root@localhost ~]# grep a[^0-9]  test.txt
aaabbblove

//转义匹配
[root@localhost ~]# grep www\.  test.txt
www.love.com
[root@localhost ~]# cat >>./test.txt<<eof
l*o*v*e
eof
[root@localhost ~]# grep * test.txt
[root@localhost ~]# grep \* test.txt
[root@localhost ~]# l*o*v*e
//单引号和双引号这里作用相同
[root@localhost ~]# grep "*" test.txt
[root@localhost ~]# l*o*v*e
[root@localhost ~]# grep '*' test.txt
[root@localhost ~]# l*o*v*e

2.拓展元字符

(示例在grep正则过滤)

字符 功能 示例
+ 匹配一次或多次前导字符 [a-z]+ove
? 匹配零次或一次前导字符 lo?ve
a|b 匹配a或b love|hate
x{m} 字符x重复m次 o{5}
x{m,} 字符x重复至少m次 o{5,}
x{m,n} 字符x重复m到n次 o{5,10}
() 字符组

3.正则判断=~

[root@localhost ~]# num1=1 
//运用正则,判断需要[[ ]]
//注意:^在[]内表示取反,^在[]外表示以什么开头
//=~ 用于正则表达式匹配
[root@localhost ~]# [[ $num1 =~ ^[0-9] ]] && echo "yes" || echo "no"
yes
[root@localhost ~]# [[ $num1 =~ [^0-9] ]] && echo "yes" || echo "no"
no


[root@localhost ~]# num3=1b1 
[root@localhost ~]# [[ $num3 =~ ^[0-9] ]] && echo "yes" || echo "no"
yes
[root@localhost ~]# [[ $num3 =~ ^[0-9]+$ ]] && echo "yes" || echo "no"
no    //num3是纯数字,这里才会是yes
[root@localhost ~]# [[ $num3 =~ [^0-9] ]] && echo "yes" || echo "no"
yes
[root@localhost ~]# [[ $num3 =~ ^[^0-9] ]] && echo "yes" || echo "no"
no
[root@localhost ~]# [[ $num3 =~ ^[0-9][a-z][0-9]+$ ]] && echo "yes" || echo "no"
yes

//或:
if [[ $num3 =~ ^[0-9]+$ ]];then  echo "yes" ;else echo 'no'; fi

[root@localhost ~]# num=1.6
[root@localhost ~]# [[ $num =~ ^[0-9]\.[0-9]+$ || $num =~ ^[0-9]+$ ]] && echo "yes" || echo "no"       //输入的只能是数字(包括小数)
yes
[root@localhost ~]# [[ $num =~ . && echo "yes" || echo "no"
yes    //1.6作为字符串被匹配

你可能感兴趣的:(Shell,正则表达式,运维,bash,centos,linux)