编程教程
你的位置: 中国个人站长站 -- 网络编程 -- PHP教程 -- 教程正文 揭开正则表达式语法的神秘面纱
推荐位

揭开正则表达式语法的神秘面纱

中国个人站长站 PHP教程 点击数: 更新时间:2007-7-29 20:17:45
ill match “nerd” and “neerd”



锚是指它所要匹配的格式,如图C所示。使用它能方便你查找通用字符的合并。例如,我用vi行编辑器命令:s来代表substitute,这一命令的基本语法是:

s/pattern_to_match/pattern_to_substitute/


Table C: Regular expression anchors

操作
解释
例子
结果

^
Match at the beginning of a line
s/^/blah /
Inserts “blah “ at the beginning of the line

$
Match at the end of a line
s/$/ blah/
Inserts “ blah” at the end of the line

\<
Match at the beginning of a word
s/\</blah/
Inserts “blah” at the beginning of the word



egrep “\<blah” sample.txt
Matches “blahfield”, etc.

\>
Match at the end of a word
s/\>/blah/
Inserts “blah” at the end of the word



egrep “\>blah” sample.txt
Matches “soupblah”, etc.

\b
Match at the beginning or end of a word
egrep “\bblah” sample.txt
Matches “blahcake” and “countblah”

\B
Match in the middle of a word
egrep “\Bblah” sample.txt
Matches “sublahper”, etc.




间隔

Res中的另一可便之处是间隔(或插入)符号。实际上,这一符号相当于一个OR语句并代表|符号。下面的语句返回文件sample.txt中的“nerd” 和 “merd”的句柄:

egrep “(n|m)erd” sample.txt


间隔功能非常强大,特别是当你寻找文件不同拼写的时候,但你可以在下面的例子得到相同的结果:

egrep “[nm]erd” sample.txt

当你使用间隔功能与Res的高级特性连接在一起时,它的真正用处更能体现出来。

一些保留字符
Res的最后一个最重要特性是保留字符(也称特定字符)。例如,如果你想要查找“ne*rd”和“ni*rd”的字符,格式匹配语句“n[ei]*rd”与“neeeeerd” 和 “nieieierd”相符合,但并不是你要查找的字符。因为‘*’(星号)是个保留字符,你必须用一个反斜线符号来替代它,即:“n[ei]\*rd”。其它的保留字符包括:

^ (carat)
. (period)
[ (left bracket}
$ (dollar sign)
( (left parenthesis)
) (right parenthesis)
| (pipe)
* (asterisk)
+ (plus symbol)
? (question mark)
{ (left curly bracket, or left brace)
\ backslash
一旦你把以上这些字符包括在你的字符搜索中,毫无疑问Res变得非常的难读。比如说以下的PHP中的eregi搜索引擎代码就很难读了。

eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$sendto)

你可以看到,程序的意图很难把握。但如果你抛开保留字符,你常常会错误地理解代码的意思。

总结
在本文中,我们揭开了正则表达式的神秘面纱,并列出了ERE标准的通用语法。如果你想阅览Open Group组织的规则的完整描述,你可以参见:Regular Expressions,欢迎你在其中的讨论区发表你的问题或观点。

上一页  [1] [2] 

教程录入:swh    责任编辑:swh 
个人站长站与你风雨同舟!
本站所提供的资源均来源于互联网,如有侵权行为,请与本站管理员联系,我们会第一时间删除!
·如果您发现《揭开正则表达式语法的神秘面纱》文章有错误,也请通知我们修改!
联系邮箱chinageren#126.com,谢谢支持!
站内搜索:
广告服务 | 友情链接 | 联系我们 | 免责声明 | 用户留言 | 网站导航
版权所有:中国个人站长站 2007-2008 未经授权禁止复制或建立镜像 客服QQ号:112731235
copyright © 2007-2008 www.ChinaGeRen.com online services. all rights reserved. 苏ICP备05000059号