正则表达式(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” 大写
匹配任何非空白字符