perl环视(断言)

每次写断言相关匹配都查一下文档,还老实点记在自己blog吧

$ vi test.pl  
#!/usr/bin/perl
USE warnings;
USE strict;
my $line = "alovebcliked";
#(?=EXP)断言自身出现的位置的后面能匹配表达式EXP
IF ( $line =~ /(\w+)(?=love)/ ){
  print "matched one:$1\n";
}
#(?<=EXP)断言自身出现的位置的前面能匹配表达式EXP
IF ($line =~ /(?<=LIKE)\d/){
  print "matched two\n";
}
elsif($line =~ /(?<=LIKE)(\w+)/){
  print "matched two two:$1\n";
}
 
$line = "abc123";
#(?!EXP)断言此位置的后面不能匹配表达式EXP
IF ($line =~ /([a-z]{2})(?!\d+)/){
   print "matched three:$1\n";
}
IF ($line =~ /([a-z]{3})(?!\d+)/){
   print "matched three three:$1\n";
}
$line = "123abc";
#(?<!EXP)断言此位置的前面不能匹配表达式
IF ($line =~ /(?<![a-z])([a-z]{3})/){
   print "matched four:$1\n";
}
$ perl test.pl
matched one:a
matched two two:d
matched three:ab
matched four:abc

Post a Comment