字符匹配:
.: 匹配任意单个字符;
[root@ansible ~]# grep 'r..t' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[]: 匹配指定范围内的任意单个字符
[^]:匹配指定范围外的任意单个字符
专用字符集合:
[:digit:]:任意数字,相当于0-9
[:lower:]:任意小写字母
[:upper:]: 任意大写字母
[:alpha:]: 任意大小写字母
[:alnum:]:任意数字或字母
[:space:]:
[:punct:]:标点符号
匹配次数:用在要指定次数的字符后面,用于指定前面的字符要出现的次数;
*:匹配前面的字符任意次:
例如: grep "c*d"
[root@ansible ~]# cat test.txt
abcd
cad
aay
aad
[root@ansible ~]# grep "c*d" test.txt
abcd
cad
aad
.*:任意长度的任意字符:
[root@ansible ~]# cat test.txt
abcd
cad
aay
aad
[root@ansible ~]# grep 'a.*d' test.txt
abcd
cad
aad
\?:匹配其前面的字符0或1次;即前面的可有可无;
[root@ansible ~]# grep 'c\?d' test.txt
abcd
cad
aad
\+:匹配其前面的字符至少1次;
[root@ansible ~]# cat test.txt
abcd
cad
aay
aad
[root@ansible ~]# grep "c\+d" test.txt
abcd
\{m\}:匹配前面的字符m次;
[root@ansible ~]# grep '[[:alpha:]]\{3\}t' /etc/passwd
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
\{m,n\}:匹配前面的字符至少m次,至多n次;
[root@ansible ~]# grep '[[:alpha:]]\{1,3\}t' /etc/passwd
\{0,n\}:匹配前面的字符至多n次;
[root@ansible ~]# grep '[[:alpha:]]\{0,3\}t' /etc/passwd
\{m,\}:匹配前面的字符至少m次;
[root@ansible ~]# grep '[[:alpha:]]\{3,\}t' /etc/passwd
位置锚定:
^:行首锚定;用于模式的最左侧;
$:行尾锚定;用于模式的最右侧;
^PATTERN$: 用于模式匹配整行;
^$: 空行;
^[[:space:]]*$
< 或 \b:词首锚定;用于单词模式的左侧;
> 或 \b:词尾锚定;用于单词模式的右侧;
<PATTERN>:匹配整个单词;
分组:
():将一个或多个字符捆绑在一起,当作一个整体进行处理;
(xy)*ab
Note: 分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中,这些变量的命名方式为: \1, \2, \3, ...
\1: 从左侧起,第一个左括号以及与之匹配右括号之间的模式所匹配到的字符;
\(ab\+\(xy\)*\):
\1: ab\+\(xy\)*
\2: xy
后向引用:引用前面的分组括号中的模式所匹配字符,(而非模式本身)