Perl正则表达式超详细教程(4)

例如,字符串"abcabc",正则表达式"ab",在默认情况下(不是全局匹配)该正则在匹配到第一个ab后就结束了,如果使用了g修饰符,匹配完第一个ab,还会继续向后匹配,而且正好还能匹配到第二个ab,所以最终有两个ab被匹配成功。

要验证多次匹配,需要使用循环遍历的方式,而不能用if语句:

$name="aAbBcCaBc"; while($name =~ m/ab/gi){ print "pre match: $` \n"; print "match: $& \n"; print "post match: $' \n"; }

执行它,将输出如下内容:

pre match: a match: Ab post match: BcCabd pre match: aAbBcC match: ab post match: d

以下内容,如果仅仅只是为了学perl正则,那么可以跳过,因为很难,如果是学perl语言,那么可以继续看下去。

实际上,在开启了g全局匹配后,perl每次在成功匹配的时候都会记下匹配的字符位移,以便在下次匹配该内容时候,可以从指定位移处继续向后匹配。每次匹配成功后的位移值(pos的位移从0开始算,0位移代表的是第一个字符左边的位置),都可以通过pos()函数获取。如果本次匹配导致位移指针重置,pos将返回undef。

$name="123ab456"; $name =~ m/\d\d/g; # 第一次匹配,匹配成功后记下位移 print "matched string: $&, position: ",pos $name,"\n"; $name =~ m/\d\d/g; # 第二次匹配,匹配成功后记下位移 print "matched string: $&, position: ",pos $name,"\n";

执行它,将输出如下内容:

matched string: 12, position: 2 matched string: 45, position: 7

由于匹配失败的时候,正则匹配操作会返回假,所以可以作为if或while等的条件语句。例如,改为while循环多次匹配:

$name="123ab456"; while($name =~ m/\d\d/g){ print "matched string: $&, position: ",pos $name,"\n"; }

默认全局匹配情况下,当本次匹配失败,位移指针将重置到起始位置0处,也就是说,下次匹配将从头开始匹配。例如:

$txt="1234a56"; $txt =~ /\d\d/g; # 匹配成功:12,位移向后移两位 print "matched $&: ",pos $txt,"\n"; $txt =~ /\d\d/g; # 匹配成功:34,位移向后移两位 print "matched $&: ",pos $txt,"\n"; $txt =~ /\d\d\d/g; # 匹配失败,位移指针回到0处,pos()返回undef print "matched $&: ",pos $txt,"\n"; $txt =~ /\d/g; # 匹配成功:1,位移向后移1位 print "matched $&: ",pos $txt,"\n";

执行上述程序,将输出:

matched 12: 2 matched 34: 4 matched 34: matched 1: 1

如果"g"修饰符下同时使用"c"修饰符,也就是"gc",它表示全局匹配失败的时候不重置位移指针。也就是说,本次匹配失败后,位移指针会向后移一位,下次匹配将从后移的这个位置处开始匹配。当位移移到了结尾,将无法再移动,此时位移指针将一直指向最后一个位置。

$txt="1234a56"; $txt =~ /\d\d/g; print "matched $&: ",pos $txt,"\n"; $txt =~ /\d\d/g; print "matched $&: ",pos $txt,"\n"; $txt =~ /\d\d\d/gc; # 匹配失败,位移向后移1位,$&和pos()保留上一次匹配成功的内容 print "matched $&: ",pos $txt,"\n"; $txt =~ /\d/g; # 匹配成功:5,位移向后移1位 print "matched $&: ",pos $txt,"\n"; $txt =~ /\d/g; # 匹配成功:6,位移向后移1位 print "matched $&: ",pos $txt,"\n"; $txt =~ /\d/gc; # 匹配失败:位移无法再后移,将一直指向最后一个位置 print "matched $&: ",pos $txt,"\n";

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/e1a716f6fc1f35a6ad219d4af05ea1f5.html