Linux之正则表达式

正则表达式

正则表达式分类

  • 基本正则表达式
  • 扩展正则表达式

基本正则表

元字符
.          //任意单个字符
[root@master opt]# mkdir test
[root@master opt]# cd test/
[root@master test]# touch {1..20} {a..z}

[root@master test]# ls
1   11  13  15  17  19  20  4  6  8  a  c  e  g  i  k  m  o  q  s  u  w  y
10  12  14  16  18  2   3   5  7  9  b  d  f  h  j  l  n  p  r  t  v  x  z
[root@master test]# ls | grep '^.$'
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
[root@master test]# ls | grep '^..$'
10
11
12
13
14
15
16
17
18
19
20
[]         //匹配指定范围内的任意单个字符
[root@master test]# ls | grep '^[1]$'
1
[root@master test]# ls | grep '^[1-5]$'
1
2
3
4
5
[root@master test]# ls | grep '^[a]$'
a
[root@master test]# ls | grep '^[a-f]$'
a
b
c
d
e
f
[^]          //匹配指定范围外的任意单个字符
[root@master test]# ls | grep '^[^a-z]$'
1
2
3
4
5
6
7
8
9
匹配次数(贪婪模式)
 *           //匹配其前面的任意单个字符任意次

[root@master test]# touch abc abcc abccc abccc
[root@master test]# ls | grep '^abc*$'
ab
abc
abcc
abccc
 .*          //任意长度的任意字符
[root@master test]# touch  bc bcc bccc 
[root@master test]# ls | grep '^b.*$'
b
bc
bcc
bccc
\?          //匹配其前面的任意单个字符1次或0次
[root@master test]# ls | grep '^b\?$'
b
[root@master test]# ls | grep '^bc\?$'
b
bc
\+          //匹配其前面的任意单个字符至少1次
[root@master test]# ls | grep '^bc\+$'
bc
bcc
bccc
\{m,n\}     //匹配其前面的任意单个字符至少m次,至多n次
[root@master test]# ls | grep '^abc\{1,\}$'
abc
abcc
abccc
[root@master test]# ls | grep '^abc\{1,2\}$'
abc
abcc
[root@master test]# ls | grep '^abc\{1,3\}$'
abc
abcc
abccc    
位置锚定
^           //锚定行首,此字符后面的任意单个字符必须出现在行首
[root@master test]# ls | grep '^abc'
abc
abcc
abccc
$           //锚定行尾,此字符前面的任意单个字符必须出现在行尾
[root@master test]# ls | grep 'c$'
abc
abcc
abccc
bc
bcc
bccc
c
^$          //空白行
[root@master test]# vim a
hello  world

hehe
[root@master test]# grep '^$' a
                                            //此处是空行 
[root@master test]# grep -v '^$' a          //-v 表示取反
hello  world   //
hehe

\<或\b       //锚定词首,其后面的任意单个字符必须作为单词首部出现
\>或\b       //锚定词尾,其前面的任意单个字符必须作为单词尾部出现
[root@master test]# vim b
hello yxt hello cl hello tom hello hehe
[root@master test]# grep '^hello' b        //只有每一行的第一个才会被匹配
hello yxt hello cl hello tom hello hehe
[root@master test]# grep '\bhello' b       //所有的被匹配
hello yxt hello cl hello tom hello hehe
分组
\(\)        //后向引用
[root@master test]# touch ab abab ababab abababab
[root@master test]# ls | grep '^\(ab\)*$'
ab
abab
ababab
abababab

\1      //引用第一个左括号以及与之对应的右括号所包括的所有内容
\2      //引用第二个左括号以及与之对应的右括号所包括的所有内容
[root@master test]# echo 'hello world yexiaotian'
hello world yexiaotian
[root@master test]# echo 'hello world yexiaotian' | sed 's/hello \(.*\) \(.*\)/hello \2 \1/'
hello yexiaotian world
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值