正则表达式的语法

字符匹配

 

字符匹配


正则表达式的关键之处在于确定你要搜索匹配的东西,如果没有这一概念,Res将毫无用处。

每一个表达式都包含需要查找的指令,如表A所示。

Table A: Character-matching regular expressions

操作

解释

例子

结果

.

Match any one character

grep .ord sample.txt

Will match “ford”, “lord”, “2ord”, etc. in the file sample.txt.

[ ]

Match any one character listed between the brackets

grep [cng]ord sample.txt

Will match only “cord”, “nord”, and “gord”

[^ ]

Match any one character not listed between the brackets

grep [^cn]ord sample.txt

Will match “lord”, “2ord”, etc. but not “cord” or “nord”

grep [a-zA-Z]ord sample.txt

Will match “aord”, “bord”, “Aord”, “Bord”, etc.

grep [^0-9]ord sample.txt

Will match “Aord”, “aord”, etc. but not “2ord”, etc.


重复操作符

重复操作符,或数量词,都描述了查找一个特定字符的次数。它们常被用于字符匹配语法以查找多行的字符,可参见表B。

Table B: Regular expression repetition operators

操作

解释

例子

结果

?

Match any character one time, if it exists

egrep “?erd” sample.txt

Will match “berd”, “herd”, etc. and “erd”

*

Match declared element multiple times, if it exists

egrep “n.*rd” sample.txt

Will match “nerd”, “nrd”, “neard”, etc.

+

Match declared element one or more times

egrep “[n]+erd” sample.txt

Will match “nerd”, “nnerd”, etc., but not “erd”

{n}

Match declared element exactly n times

egrep “[a-z]{2}erd” sample.txt

Will match “cherd”, “blerd”, etc. but not “nerd”, “erd”, “buzzerd”, etc.

{n,}

Match declared element at least n times

egrep “.{2,}erd” sample.txt

Will match “cherd” and “buzzerd”, but not “nerd”

{n,N}

Match declared element at least n times, but not more than N times

egrep “n[e]{1,2}rd” sample.txt

Will match “nerd” and “neerd”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值