【发布时间】:2009-08-18 21:59:43
【问题描述】:
我有一些代码可以抓取一些文本的“中间”;
具体来说,在foo $someword 和下一个foo $someword 之间。
但是,发生的情况是它卡在第一个“中间”处,并且不知何故内部字符串位置没有增加。
输入数据是一个带有换行符的文本文件:它们无关紧要,但使打印更容易。
my $component = qr'foo (\w+?)\s*?{';
while($text =~ /$component/sg)
{
push @baz, $1; #grab the $someword
}
my $list = join( "|", @baz);
my $re = qr/$list/; #create a list of $somewords
#Try to grab everything between the foo $somewords;
# or if there's no $foo someword, grab what's left.
while($text=~/($re)(.+?)foo ($re|\z|\Z)/ms)
#if I take out s, it doesn't repeat, but nothing gets grabbed.
{
# print pos($text), "\n"; #this is undef...that's a clue I'm certain.
print $1, ":", $2; #prints the someword and what was grabbed.
print "\n", '-' x 20, "\n";
}
【问题讨论】:
-
你不想在第二个循环中也添加一个“/g”修饰符吗?
-
\z 和 \Z 不是必需的,\Z 包含 \z
-
我正在浏览文本,而不是抓取数组(这是 /g 将返回的内容)。但是,/g 不会影响最终输出问题。我试过了。 :-)
-
@chas:将其修改为 \Z 并添加 \g 使其循环一次。删除 \g 使其无限循环。