Linux_正则表达式(1.基础正则表达式)

正则表达式(1)

正则表达式:用某种模式去匹配一类字符串的公式,它是用一串字符串和元字符构成的字符串。元字符就是描述字符表达式的内容、转换和描述各种操作信息的字符。

1.基础的正则表达式

“.”(点号)
  匹配除换行符之外的任意一个字符。
 

# "r..t" : 匹配root,r  t,raat等中间是任意两个字符
niostar@ubuntu:~$ cat /etc/passwd | grep "r..t" 
root:x:0:0:root:/root:/bin/bash

“*”(星号)
  匹配前一个字符0次或者任意多次。
 

# "r*t" : 匹配t,rt,rrt,rrrt等
niostar@ubuntu:~$ cat /etc/passwd | grep "r.*t" | grep root
root:x:0:0:root:/root:/bin/bash

“\{n,m\}”
  精确匹配前一个字符出现的次数

\{n\},匹配前面字符出现n次    

\{n,\},匹配前面字符出现大于n次 

\{n,m\},匹配前面字符出现n次到m次之间 

niostar@ubuntu:~$ cat /etc/passwd | grep "ro\{2\}t" o出现2次
root:x:0:0:root:/root:/bin/bash
niostar@ubuntu:~$ cat /etc/passwd | grep "ro\{2,10\}t" o出现2到10次
root:x:0:0:root:/root:/bin/bash
niostar@ubuntu:~$ cat /etc/passwd | grep "ro\{2,\}t"  o出现大于2次
root:x:0:0:root:/root:/bin/bash
niostar@ubuntu:~$ cat /etc/passwd | grep "ro\{3,\}t" o出现大于3次
niostar@ubuntu:~$ 

“^”
  匹配开头的字符

# "^root" : 匹配rootrr,root.*等
niostar@ubuntu:~$ cat /etc/passwd | grep "^root"
root:x:0:0:root:/root:/bin/bash

“$”
  匹配结尾的字符

# "bash$" : 匹配....bash等
niostar@ubuntu:~$ cat /etc/passwd | grep "bash$"
root:x:0:0:root:/root:/bin/bash
niostar:x:1000:1000:Ubuntu12,,,:/home/niostar:/bin/bash
guest-XhctQ5:x:118:126:Guest,,,:/tmp/guest-XhctQ5:/bin/bash
guest-CCDtQS:x:119:127:Guest,,,:/tmp/guest-CCDtQS:/bin/bash
guest-f39d83:x:121:129:Guest,,,:/tmp/guest-f39d83:/bin/bash
guest-k8q0bT:x:122:130:Guest,,,:/tmp/guest-k8q0bT:/bin/bash

“[]”
  匹配括号内出现的任一字符

[^] 代表取反

“^1[38][0-9]\{9\}” 代表了以1开头,第二位是3或者8后面9位任意数字

“\”
  代表转义

[\ -]  匹配空格或者-

“\<” “\>”

# "\<hello" 匹配以hello开头的单词
# "hello\>" 匹配以hello结尾的单词
# "\<hello\>" 精确匹配hello
niostar@ubuntu:~/chenqian/shell$ echo helloworld | grep "\<hello"
helloworld
niostar@ubuntu:~/chenqian/shell$ echo helloworld | grep "hello\>"
niostar@ubuntu:~/chenqian/shell$ echo helloworld | grep "\<hello\>" 无法匹配
niostar@ubuntu:~/chenqian/shell$ echo hello | grep "\<hello\>"  匹配成功
hello

“\d”
  匹配一个数字相当于[0-9],但是要加-P

niostar@ubuntu:~/chenqian/shell$ echo 123 | grep '\d'
niostar@ubuntu:~/chenqian/shell$ echo 123 | grep -P '\d'
123
niostar@ubuntu:~/chenqian/shell$ 

“\b”
  匹配单词的边界

niostar@ubuntu:~/chenqian/shell$ echo "hello world" | grep '\bhello\b'
hello world
niostar@ubuntu:~/chenqian/shell$ echo "hello world" | grep '\bhello'
hello world
niostar@ubuntu:~/chenqian/shell$ echo "helloworld" | grep '\bhello'
helloworld
niostar@ubuntu:~/chenqian/shell$ echo "helloworld" | grep '\bhello\b'
niostar@ubuntu:~/chenqian/shell$ 

“\B”
  匹配非单词的边界

“\w”小写w
  匹配字母数字下划线 相当于[A-Za-z0-9_]

“\W”大写w
  匹配非字母数字下划线 相当于[^A-Za-z0-9_]

“\n”
  匹配换行符

“\s” 小写
  匹配任何空白字符

“\S” 大写
  匹配任何非空白字符

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值