shell之正则表达式

241 阅读1分钟

1. 认识正则表达式

通常用于判断语句中,用来检查某一字符串是否满足某一格式

  • 正则表达式是由普通字符与元字符组成

普通字符包括大小写字母、数字、标点符号及一些其他符号

元字符是指在正则表达式中具有特殊意义的专用字符,可以用来规定其前导字符(即位于元字符前面的字符或表达式)在目标对象中的出现模式

2. 基础正则表达式常见元字符

支持的工具: grep、 egrep、 sed、 awk

  • \:转义字符

用于取消特殊符号的含义例: \!、\n、\$

  • ^:匹配字符串开始的位置

^a、^the、^#、^[a-z]

[root@localhost 1]# grep "^g" 3.txt 

image.png

  • $:匹配字符串结束的位置

word$、^$匹配空行

[root@localhost 1]# grep "d$" 3.txt

image.png

  • .:匹配除\n之外的任意的一个字符

go.d、 g..d

[root@localhost 1]# grep "go.d" 3.txt 
[root@localhost 1]# grep "g..d" 3.txt

image.png

  • *:匹配前面子表达式0次或者多次

goo*d、 go.*d

[root@localhost 1]# grep "go*d" 3.txt 
[root@localhost 1]# grep "go.*d" 3.txt 

image.png

  • [list]:匹配list列表中的一个字符

go[ola]d、[abc]、[a-z]、[a-z0-9]、[0-9]匹配任意一位数字

[root@localhost 1]# grep "[abc]" 3.txt 
[root@localhost 1]# grep "[0-9]" 3.txt 
[root@localhost 1]# grep "[a-z0-9]" 3.txt 

image.png

  • [^list]:匹配任意非list列表中的一个字符

[^0-9]、[^A-Z0-9]、[^a-z]匹配任意一 位非小写字母

[root@localhost 1]# grep "^[a-z]" 3.txt

image.png

  • \{n\}:匹配前面的子表达式n次

go\{2\}d、'[0-9]\{2\}'匹配两位数字

[root@localhost 1]# grep "go\{2\}d" 3.txt 
[root@localhost 1]# grep "[0-9]\{2\}" 3.txt

image.png

  • \{n,\}:匹配前面的子表达式不少于n次

go\{2,\}d、'[0-9]\{2,\}'匹配两位及两位以上数字

[root@localhost 1]# grep "go\{2,\}d" 3.txt 
[root@localhost 1]# grep "[0-9]\{2,\}" 3.txt 

image.png

  • \{n,m\}:匹配前面的子表达式n到m次

go\{2,3\}d、'[0-9]\{2,3\}'匹配两位到三位数字

[root@localhost 1]# grep "[0-9]\{2,3\}" 3.txt 
[root@localhost 1]# grep "go\{2,3\}d" 3.txt

image.png

注: egrep、awk使用{n}、{n,}、{n, m}匹配时“{}”前不用加“\”

  • \w:匹配包括下划线的任何单词字符。

  • \W:匹配任何非单词字符。等价于“[^A-8a-z0-9_ ]”。

  • \d:匹配一个数字字符。

  • \D:匹配一个非数字字符。等价于[^0-9]。

  • \s:空白符。

  • \S:非空白符

3. 扩展正则表达式元字符

(支持的工具:egrep、awk) grep -Esed -r

  • +:匹配前面子表达式1次以上

go+d将匹配至少一个o, 如god、good、goood等

[root@localhost 1]# grep -E "go+d" 3.txt

image.png

  • ?匹配前面子表达式0次或者1次

go?d将匹gd或god

[root@localhost 1]# grep -E "go?d" 3.txt

image.png

  • ():将括号中的字符串作为一个整体

g(oo)+d将匹配o整体1次以上,如good、gooood等

[root@localhost 1]# grep -E "g(oo)+d" 3.txt 

image.png

  • |:以或的方式匹配字符串

g(oo|la)d将匹配good或者gold

[root@localhost 1]# grep -E "g(oo|ol)d" 3.txt

image.png

4.综合示例

  • 座机电话正则匹配

区号025开头,号码与区号间可以是空格、-、没有,号码必须是5或者8开头的八位数

[root@localhost ~]# grep -E "^(025)[ -]?[58][0-9]{7}$"
[root@localhost ~]# grep -P "^(025)[ -]?[58]\d{7}$"

image.png