Perl正则表达式讲解,真的非常详细
www.diybl.com 时间 : 2008-09-12 作者:佚名 编辑:辉辉 点击: [ 评论 ]
9.3.1原则1
正则表达式有三种形式:匹配、替换和转换。
在表 9-1 中列有三种正则表达式运算符。
接下来对每一个表达式给出详尽解释。
匹配:m/<regexp>/这种形式表明在//内部的正则表达将用于匹配 = ~或 !~左边的标量。为了语法上的简化用/<regexp>/,略去m。
替换:s/<regexp>/<substituteText>/这种形式表明正则表达式<regexp>将被文本 <substituteText>替换,为了语法的简化用/<regexp>/<substituteText>略去s。
·转换:tr/<charClass>/<substituteClass>/这种形式包含一系列的字符—/<charClass>—同时把它们替换为<substituteClass>。
注意转换<tr>并不真正是一个正则表达式,但是对于用正则表达式难于处理的数据常使用它来进行操纵。因此,tr/[0-9]/9876543210.组成1223456789,987654321等字符串。
通过使用=~(用英语讲:does,与“进行匹配”同)和!~(英语:doesn't,与“不匹配”同)把这些表达式捆绑到标量上。作为这种类型的例子,下面我们给出六个示例正则表达式及相应的定义:
$scalarName =~ s/a/b; # substitute the character a for b, and return true if this can happern
$scalarName =~ m/a; # does the scalar $scalarName have an a in it?
$scalarName =~ tr/A-Z/a-z/; # translate all capital letter with lower case ones, and return ture if this happens
$scalarName !~ s/a/b/; # substitute the character a for b, and return false if this indeed happens.
$scalarName !~ m/a/; # does the scalar $scalarName match the character a? Return false if it does.
$scalarName !~ tr/0-9/a-j/; # translate the digits for the letters a thru j, and return false if this happens.
如果我们输入像 horned toad =~ m/toad/ 这样的代码,则出现图 9-1 所示情况:
另外,如果读者正在对特定变量 $_ 进行匹配(读者可能在while循环,map或grep中使用),则可以不用!~和=~。因而,以下所有代码都会合法:
my @elemente = (' al' ,' a2' ,' a3' ,' a4' ,' a5' );
foreach (@elements) {s/a/b/;}
程序使 @elements 等于b1,b2.b3,b4,b5。另外:
while(<$FD>) {print if (m/ERBOR/);}
打印所有包含 error 字符串的行:
if (grep(/pattern/, @lines)) {print " the variable \@lines has pattern in it!\n";}
打印所有包含模式pattern内容的行,这直接引入下一原则。
9.3.2 原则2
正则表达式仅在标量上匹配。
注意这里标量的重要性,如果读者试一试如下代码:
@arrayName = (' variablel', 'variable2');
@arrayName =~ m/variable/; # looks for ' variable' in the array? No! use grep instead
那么@arrayName匹配不成功! @arrayName被Perl解释为2,于是这意味着读者在输入:
' 2' =~ m/variable/;
至少讲这不能给出预想的结果。如果读者想这样做,输人为:
grep(m/variable/, @arrayName);
该函数通过@arrayName中的每一个元素进行循环,返回(在标量环境中)匹配的次数,同时在数组环境中返回匹配元素的实际列表。