欢迎来到天天文库
浏览记录
ID:14484197
大小:36.00 KB
页数:4页
时间:2018-07-29
《perl教程 -- 字符串匹配》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、窗体顶端窗体底端字符串匹配---摘自《网猴》Perl的最有用的特征之一是它的强大的字符串处理能力。其中的核心是被很多其它UNIX工具使用的规则表达式(regularexpression-RE)。规则表达式规则表达式包含在斜线内,匹配通过=~操作符进行。如果字符串the出现在变量$sentence中,则下面的表达式为真:$sentence=~/the/RE是大小写敏感的,所以如果$sentence="Thequickbrownfox";那么上面的匹配结果为false。操作符!~用在“非匹配”时,在上面的例子中$sentence!~/th
2、e/是真,因为字符串the没有出现在$sentence中。特殊变量$_在条件语句if($sentence=~/under/){print"We'retalkingaboutrugby";}中,如果我们有下面两个表达式中的一个:$sentence="Upandunder";$sentence="BestwinklesinSunderland";将打印出一条信息。但是如果我们把这个句子赋值给特殊变量$_,用起来会更容易些。如果这样,我们可以避免使用匹配和非匹配操作符,上面的例子可以写成:if(/under/){print"We'ret
3、alkingaboutrugby";}$_变量是很多Perl操作的缺省变量,经常被使用。其它的RE在RE中有大量的特殊字符,既使它们功能强大,又使它们看起来很复杂。最好在用RE时慢慢来,对它们的使用是一种艺术。下面是一些特殊的RE字符和它们的意义:.#Anysinglecharacterexceptanewline^#Thebeginningofthelineorstring$#Theendofthelineorstring*#Zeroormoreofthelastcharacter+#Oneormoreofthelastchar
4、acter?#Zerooroneofthelastcharacter下面是一些匹配的例子,在使用时应加上/.../:t.e#tfollowedbyanthingfollowedbye#Thiswillmatchthe#tre#tle#butnotte#tale^f#fatthebeginningofaline^ftp#ftpatthebeginningofalinee$#eattheendofalinetle$#tleattheendofalineund*#unfollowedbyzeroormoredcharacters#Thisw
5、illmatchun#und#undd#unddd(etc).*#Anystringwithoutanewline.Thisisbecause#the.matchesanythingexceptanewlineand#the*meanszeroormoreofthese.^$#Alinewithnothinginit.还有更多的用法。方括号用来匹配其中的任何一个字符。在方括号中"-"表明"between","^"表示"not":[qjk]#Eitherqorjork[^qjk]#Neitherqnorjnork[a-z]#Anythi
6、ngfromatozinclusive[^a-z]#Nolowercaseletters[a-zA-Z]#Anyletter[a-z]+#Anynon-zerosequenceoflowercaseletters上面提到的已经基本够用了,下面介绍的只做参考:竖线"
7、"表示"or",括号(...)可以进行集合:jelly
8、cream#Eitherjellyorcream(eg
9、le)gs#Eithereggsorlegs(da)+#Eitherdaordadaordadadaor...下面是一些其它的特殊字符:#Anewlinet
10、#Atabw#Anyalphanumeric(word)character.#Thesameas[a-zA-Z0-9_]W#Anynon-wordcharacter.#Thesameas[^a-zA-Z0-9_]d#Anydigit.Thesameas[0-9]D#Anynon-digit.Thesameas[^0-9]s#Anywhitespacecharacter:space,#tab,newline,etcS#Anynon-whitespacecharacterb#Awordboundary,outside[]on
11、lyB#Nowordboundary象$,
12、,[,),,/这样的字符是很特殊的,如果要引用它们,必须在前面加一个反斜线:
13、#Verticalbar[#Anopensquarebracket)#Aclosingp
此文档下载收益归作者所有