加入收藏 | 设为首页 | 会员中心 | 我要投稿 银川站长网 (https://www.0951zz.com/)- 云通信、基础存储、云上网络、机器学习、视觉智能!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

深入解析 Linux 中运用正则表達式的情境

发布时间:2023-09-27 13:00:23 所属栏目:Linux 来源:
导读:深入解析 Linux 中运用正则表達式的情境:1、组成普通字符:普通字符串,没有特殊含义特殊字符:在正则表达式中具有特殊的含义正则表达式中常见的meta字符【特殊字符】2、POSIX BRE【基本】与ERE【扩展】中都有的met

深入解析 Linux 中运用正则表達式的情境:

1、组成

普通字符:普通字符串,没有特殊含义

特殊字符:在正则表达式中具有特殊的含义

正则表达式中常见的meta字符【特殊字符】

2、POSIX BRE【基本】与ERE【扩展】中都有的meta字符

/ :通常用于打开或关闭后续字符的特殊含义,如(...)【/是转义字符,去掉符号的特殊意义,()、{}等在shell中都有特殊的意义】

.和以及.的区别:

[root@localhost ~]# cat -n test.txt

    1 gd

    2 god

    3

    4 good

    5 goood

    6 goad

    7

    8 gboad

2.1、. :匹配任意单个字符(除null,即不能为空)

[root@localhost ~]# grep -n "." test.txt      

1:gd

2:god

4:good

5:goood

6:goad

8:gboad

[root@localhost ~]# grep -n "go.d" test.txt

4:good

6:goad

2.2、 :匹配其前字符任意次,如o,可以是没有o或者一个o,也可以是多个o

[root@localhost ~]# grep -n "*" test.txt

[root@localhost ~]# grep -n "o*" test.txt

1:gd

2:god

3:

4:good

5:goood

6:goad

7:

8:gboad

[root@localhost ~]# echo "gbad" >>test.txt

[root@localhost ~]# echo "pbad" >>test.txt

[root@localhost ~]# echo "kgbad" >>test.txt

[root@localhost ~]# echo "poad" >>test.txt  

[root@localhost ~]# grep -n "go*" test.txt 【o可以没有,o前面的g一定要匹配】

1:gd

2:god

4:good

5:goood

6:goad

8:gboad

9:gbad

11:kgbad

*2.3、. :匹配任意字符(匹配所有),可以为空**

[root@localhost ~]# grep -n ".*" test.txt

1:gd

2:god

3:

4:good

5:goood

6:goad

7:

8:gboad

9:gbad

10:pbad

11:kgbad

12:poad

[root@localhost ~]# grep -n "go.*" test.txt

2:god

4:good

5:goood

6:goad

[root@localhost ~]# grep -n "po.*" test.txt 

12:poad

[root@localhost ~]# echo "pgoad" >>test.txt   

[root@localhost ~]# grep -n "go.*" test.txt 【匹配go后存在任意字符,可为空】

2:god

4:good

5:goood

6:goad

13:pgoad

[root@localhost ~]#

[root@localhost ~]# grep -n "o.*" test.txt 

2:god

4:good

5:goood

6:goad

8:gboad

12:poad

2.4、^ :匹配紧接着后面的正则表达式,以...为开头

[root@localhost tmp]# grep "^root" /etc/passwd

root:x:0:0:root:/root:/bin/bash

[root@localhost tmp]#

2.5、$ :匹配紧接着前面的正则表达式,以...结尾

[root@localhost tmp]# grep "bash$" /etc/passwd | head -1

(编辑:银川站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章