正则表达式

正则表达式

正则表达式分类

正则表达式:REGEXP,REGular EXPression。
正则表达式分为两类:

  • Basic REGEXP(基本正则表达式)
  • Extended REGEXP(扩展正则表达式)

基本正则表达式

元字符

 .           //任意单个字符

[root@slave1 ~]# mkdir test
[root@slave1 ~]# cd test
[root@slave1 test]# touch {1..10} {a..z}
[root@slave1 test]# ls
1   2  4  6  8  a  c  e  g  i  k  m  o  q  s  u  w  y
10  3  5  7  9  b  d  f  h  j  l  n  p  r  t  v  x  z
[root@slave1 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@slave1 test]# ls |grep '^..$'
10
[]         //匹配指定范围内的任意单个字符

[root@slave1 test]# ls |grep '^[1]$'
1
[root@slave1 test]# ls |grep '^[1-9]$'
1
2
3
4
5
6
7
8
9
[root@slave1 test]# ls |grep '^[19]$'
1
9
[^]          //匹配指定范围外的任意单个字符

[root@slave1 test]# ls |grep '^[^1-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@slave1 test]# touch abc abcc abccc abcccc
[root@slave1 test]# ls |grep '^abc*$'
abc
abcc
abccc
abcccc
.*          //任意长度的任意字符

[root@slave1 test]# ls |grep '^a.*$'
a
abc
abcc
abccc
abcccc
\?          //匹配其前面的任意单个字符1次或0次

[root@slave1 test]# ls |grep '^ab\?c$'
abc
ac
\+          //匹配其前面的任意单个字符至少1次

[root@slave1 test]# ls |grep '^ab\+c$'
abbbc
abbc
abc
\{m,n\}     //匹配其前面的任意单个字符至少m次,至多n次

[root@slave1 test]# ls |grep '^ab\{1,\}c$'
abbbc
abbc
abc
[root@slave1 test]# ls |grep '^ab\{1,2\}c$'
abbc
abc

位置锚定

^           //锚定行首,此字符后面的任意单个字符必须出现在行首

[root@slave1 test]# ls |grep '^a'
a
abbbc
abbc
abc
abcc
abccc
abcccc
ac
$           //锚定行尾,此字符前面的任意单个字符必须出现在行尾

[root@slave1 test]# ls |grep 'c$'
abbbc
abbc
abc
abcc
abccc
abcccc
ac
c
^$          //空白行

[root@slave1 test]# grep '^$' a


[root@slave1 test]# grep -v '^$' a  //-v取反
hello
hello
hello
\<\b       //锚定词首,其后面的任意单个字符必须作为单词首部出现
\>\b       //锚定词尾,其前面的任意单个字符必须作为单词尾部出现

[root@slave1 test]# cat a
hello dd hello aa hello aas hello sss
[root@slave1 test]# grep '\hello' a
hello dd hello aa hello aas hello sss
[root@slave1 test]# grep '\bh' a
hello dd hello aa hello aas hello sss
[root@slave1 test]# grep 'o\b' a
hello dd hello aa hello aas hello sss

分组

\(\)        //后向引用

[root@slave1 test]# touch ab abab ababab
[root@slave1 test]# ls |grep '^\(ab\)\+$'
ab
abab
ababab
[root@slave1 test]# ls |grep '^\(ab\)\?$'
ab
\1      //引用第一个左括号以及与之对应的右括号所包括的所有内容
\2      //引用第二个左括号以及与之对应的右括号所包括的所有内容

[root@slave1 test]# cat a
hello ss dd 
[root@slave1 test]# sed 's/hello \(.*\) \(.*\) /hello \2 \1/g' a
hello dd ss
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值