regex – 使用Perl替换运算符保留捕获

前端之家收集整理的这篇文章主要介绍了regex – 使用Perl替换运算符保留捕获前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释为什么以下代码……
#!/opt/local/bin/perl
use strict;
use warnings;

my $string;

$string = "\t\t\tEntry";
print "String: >$string<\n";

$string =~ s/^(\t*)//gi;

print "\$1: >$1<\n";
print "String: >$string<\n";
print "\n";

$string = "\t\t\tEntry";

$string =~ s/^(\t*)([^\t]+)/$2/gi;

print "\$1: >$1<\n";
print "String: >$string<\n";
print "\n";

exit 0;

…产生以下输出……

String: >           Entry<
Use of uninitialized value in concatenation (.) or string at ~/sandBox.pl line 12.
$1: ><
String: >Entry<

$1: >           <
String: >Entry<

……或更直接:为什么第一次替换中的匹配值不会保留在$1中?

解决方法

我在Perl 5.12的两个实现上尝试了这个,并没有遇到问题. 5.8做了.

因为你有g选项,perl会尝试匹配模式,直到它失败.请参阅下面的调试输出.

所以它在Perl 5.8中不起作用,但这样做:

my $c1;
$string =~ s/^(\t*)/$c1=$1;''/ge;

因此,每次匹配时,它将其保存到$c1.

这就是重新’调试’告诉我的用法

Compiling REx `^(\t*)'
size 9 Got 76 bytes for offset annotations.
first at 2
   1: BOL(2)
   2: OPEN1(4)
   4:   STAR(7)
   5:     EXACT <\t>(0)
   7: CLOSE1(9)
   9: END(0)
anchored(BOL) minlen 0
Offsets: [9]
        1[1] 2[1] 0[0] 5[1] 3[1] 0[0] 6[1] 0[0] 7[0]
Compiling REx `^(\t*)([^\t]+)'
size 25 Got 204 bytes for offset annotations.
first at 2
   1: BOL(2)
   2: OPEN1(4)
   4:   STAR(7)
   5:     EXACTF <\t>(0)
   7: CLOSE1(9)
   9: OPEN2(11)
  11:   PLUS(23)
  12:     ANYOF[\0-\10\12-\377{unicode_all}](0)
  23: CLOSE2(25)
  25: END(0)
anchored(BOL) minlen 1
Offsets: [25]
        1[1] 2[1] 0[0] 5[1] 3[1] 0[0] 6[1] 0[0] 7[1] 0[0] 13[1] 8[5] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 14[1] 0[0] 15[0]
String: >                       Entry<
Matching REx `^(\t*)' against `                 Entry'
  Setting an EVAL scope,savestack=5
   0 <> <                       Entry>        |  1:  BOL
   0 <> <                       Entry>        |  2:  OPEN1
   0 <> <                       Entry>        |  4:  STAR
                           EXACT <\t> can match 3 times out of 2147483647...
  Setting an EVAL scope,savestack=5
   3 <                  > <Entry>        |  7:    CLOSE1
   3 <                  > <Entry>        |  9:    END
Match successful!
match pos=0
Use of uninitialized value in substitution iterator at - line 11.
Matching REx `^(\t*)' against `Entry'
  Setting an EVAL scope,savestack=5
   3 <                  > <Entry>        |  1:  BOL
                            Failed...
Match Failed
Freeing REx: `"^(\\t*)"'
Freeing REx: `"^(\\t*)([^\\t]+)"'

因为你试图在行的开头匹配空格,所以既不需要g也不需要i.所以你可能会尝试做别的事情.

猜你在找的Perl相关文章