正则表达式

分类:

  • 基本正则表达式:BRE
  • 扩展正则表达式:ERE
正则表达式引擎: 采用不同算法,检查处理正则表达式的软件模块,如:PCRE(Perl Compatible Regular Expressions)

正则表达式的元字符分类:字符匹配、匹配次数、位置锚定、分组帮助:man 7 regex

元字符匹配

  • 作用一:匹配括号中任意单个字符 image.png
  • 范例
[root@centos7 ~]#ls /etc/ | grep 'rc[.0-6]' rc0.d
rc1.d rc2.d rc3.d rc4.d rc5.d rc6.d rc.d rc.local

[root@centos7 ~]#ls /etc/ | grep 'rc[.0-6].' rc0.d
rc1.d rc2.d rc3.d rc4.d rc5.d rc6.d rc.d rc.local

[root@centos7 ~]#ls /etc/ | grep 'rc[.0-6]\.' rc0.d
rc1.d rc2.d rc3.d rc4.d rc5.d rc6.d

位置锚定

  • 位置锚定可以用于定位出现的位置 1690965898655.jpg
  • 范例:取出bin 单词的行
[root@centos7 ~]#grep "\<bin\>" /etc/passwd

[root@centos7 ~]#grep ^root /etc/passwd root:x:0:0:root:/root:/bin/bash

[root@centos7 ~]#cat f1.txt



123

456
[root@centos7 ~]#grep ^$ f1.txt -n 1:
2:
3:
5:

[root@centos7 ~]#grep 3$ f1.txt 123

[root@centos7 ~]#grep ^1.*3$ f1.txt 123

[root@centos7 ~]#grep ^1.3$ f1.txt 123

[root@centos7 ~]#echo google | grep ^go* google
[root@centos7 ~]#echo gooooogle | grep ^go* gooooogle
[root@centos7 ~]#grep 'in\>' /etc/passwd 
[root@centos7 ~]#grep '\<sy' /etc/passwd 
[root@centos7 ~]#grep '\<sbin\>' /etc/passwd

扩展正则表达式

匹配次数

*	#匹配前面的字符任意次,包括0次,贪婪模式:尽可能长的匹配
.*	#任意长度的任意字符
\?	#匹配其前面的字符出现0次或1次,即:可有可无
\+	#匹配其前面的字符出现最少1次,即:肯定有且 >=1 次
\{n\}	#匹配前面的字符n次
\{m,n\} #匹配前面的字符至少m次,至多n次
\{,n\}	#匹配前面的字符至多n次,<=n
\{n,\}	#匹配前面的字符至少n次

分组匹配

  • 分组:() 将多个字符捆绑在一起,当作一个整体处理,如:(root)+
  • 后向引用:分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中,这些变量的命名 方式为: \1, \2, \3, ...
\1 表示从左侧起第一个左括号以及与之匹配右括号之间的模式所匹配到的字符范例:vim替换文件信息,把 root 替换为 rooter

[root@centos7 /data ]# cat passwd root:x:0:0:root:/root:/bin/bash

第一步: vim 打开文件(vim编辑器不识别扩展正则)
第二步:使用分组引用替换信息	:%s#\(root\)#\1er#g

匹配或

  • | 竖线符号表示或
a|b	匹配a,或匹配b
 
C|cat 	匹配C,或匹配cat

(C|c)at	匹配Cat,或匹配cat

转义符 \

  • grep命令,vim命令等默认情况下,只支持基础正则表达式,不支持扩展正则表达式。 可以通过转义符 \ 对扩展表达式符号进行转义,便可让其命令支持