正则表达式详细案例
1.1 在虚拟机中 vim hello.txt
hello world
are you ok?
areyou ok?
areyou are youok?
aaare you ok?
aare you ok
aaaare you ok
abcre you ok?
xxre you ok
are yyyou ok?
xk
zk
ok
yk
zzk
zxzxk
bxx
cxx
dxx
areyou are youok?
zk kz 1
kz zk 2
okk koo 3
zkkz
kzzk
编辑完毕,文件的准备操作
cp /etc/profile . #复制文件到当前目录
grep "after" profile #查找文件内的包含该单词的行
grep -n "after" profile #添加查找的行在文档的行号。
-v表示不包含的
[root@bk1 ~]# grep -v "after" profile | grep "after"
[root@bk1 ~]# grep -v "pathmunge" profile | grep "after"
if [ "$2" = "after" ] ; then
1.2 基本操作匹配符
匹配符:
-
\ 转义字符 \+ \ < \> #转 \后面的内容
-
. 匹配任意单个字符
-
[1234abc],[^1234],[1-5],[a-d] 字符序列单字符占位
-
^ 行首 ^.k
-
$行尾 行尾 .k$
-
\<,\>,\<abc,abc\>,\<are\> 单词首尾边界 okhelloworld ok hello world
-
| 连接操作符,并集 (\<are\>)| (\<you\>)
-
(,) 选择操作符
匹配are aare xre,0到多个a字符
grep "a*re" hello.txt
匹配“a任意单个字符re”
grep "a.re" hello.txt
匹配a一个到多个任意字符re
[root@bk1 ~]# grep "a+re" hello.txt
但是发现查询不出来,为什么?把+看成表达式了
1.3 重复操作符
1.* 匹配0到多次
2.? 匹配0到1次
3.+ 匹配1到多次
4.{n} 匹配n次
5.{n,} 匹配n到多次
6.{m,n} 匹配 m 到 n 次
粗体是扩展匹配,其他是基本匹配。
与扩展正则表达式的区别: grep (basic grep默认工作于基本模式 )
-E 选项让grep工作于扩展模式
解决上文查询不出来的遗留问题:
[root@bk1 ~]# grep -E "a+re" hello.txt
或者
[root@bk1 ~]# grep "a\+re" hello.txt
由于基本正则表达式中元字符
?,+,{,|,(和)丢失了特殊意义,需要加\,反斜杠:
?,\+,\{,\|,\(,以及\),扩展模式不需要加反斜杠
所有字母和数字匹配自身,元字符可以添加\转义
[a-d]匹配abcd中的一个
[^a-d]匹配不是abcd中的任意一个的字符
需要注意:要使用[a-d]是abcd任意一个的传统方括号表达式的解释,需要设定环境变量:LC_ALL的值是C。参考:https://www.cnblogs.com/wajika/p/6592659.html
1.4 案例
匹配包含bcd中任意一个字符的行
grep "[b-d]" hello.txt
基本正则模式,查找带问号的行
grep "?" hello.txt
.不代表重复,任意一个字符
grep "a.re" hello.txt
grep "a..re" hello.txt
grep "..re" hello.txt
grep "…re" hello.txt
匹配zk和xk
grep "[xz]k" hello.txt
匹配不是zk和xk的
grep "\<[^zx]k" hello.txt
匹配行首,该行第二个字符一定得是k
grep "^.k" hello.txt
匹配行尾,
grep ".k$" hello.txt #该行最少两个字符,最后一个是k
匹配单词边界
grep "\<are\>" hello.txt
匹配单词开头:
grep "\<are" hello.txt
匹配单词尾:
grep "re\>" hello.txt
grep "\<a*re\>" hello.txt # *表示0到多次,单词以a字符开头,或者不以a字符开头
grep "\<you\>" hello.txt
连接操作,取并集
grep -E "(\<a*re\>)|(\<you\>)" hello.txt
grep -E "a{3}" hello.txt #匹配该行中3个a重复的
grep -E "a{3,}" hello.txt
grep -E "a{3}" hello.txt
1.5 课后练习
aaa?匹配aa,aaa
grep -E "\\<aaa?re" hello.txt #以aa或aaa开头并带有re的单词的行
aare aaare aaaare
grep -E "aaa?" hello.txt #包含aa或aaa的行
grep "aaa\?" hello.txt
匹配一次到多次:aaa和aaaa
grep "aaa\+" hello.txt
扩展模式:
grep -E "aaa+" hello.txt
将匹配1次到多次的+再转义为+字符匹配
匹配0到任意多次
aaa*匹配aa,aaa,aaaa
匹配任意字符
grep -E "*" hello.txt