我不知道按照你所描述的(“最后6位数字”)回答还是假设它符合你展示的模式。所以我决定两种方式都回答。
这里有一种方法可以处理比你的示例更多样化的行。
use FileHandle;
my $jpeg_RE = qr{
(.*?) # Anything, watching out for patterns ahead
s+ # At least one space
(?> http:// ) # Once we match "http://" we re onto the next section
S*? # Any non-space, watching out for what follows
( (?: d+ / )* # At least one digit, followed by a slash, any number of times
d+ # another group of digits
) # end group
D*? # Any number of non-digits looking ahead
.jpg # literal string .jpg
s+ # At least one space
(.*) # The rest of the line
}x;
my $infile = FileHandle->new( "<$file_in" );
my $outfile = FileHandle->new( ">$file_out" );
while ( my $line = <$infile> ) {
my ( $pre_text, $digits, $post_text ) = ( $line =~ m/$jpeg_RE/ );
$digits =~ s/D//g;
$outfile->printf( "$pre_text php?id=%s $post_text
", substr( $digits, -6 ));
}
$infile->close();
然而,如果它像您展示的一样正规,那就容易得多了:
use FileHandle;
my $jpeg_RE = qr{
(?> Qhttp://pics1.riyaj.com/thumbs/E )
d{3}
/
( d{3} )
/
( d{3} )
S*?
.jpg
}x;
my $infile = FileHandle->new( "<$file_in" );
my $outfile = FileHandle->new( ">$file_out" );
while ( my $line = <$infile> ) {
$line =~ s/$jpeg_RE/php?id=$1$2/g;
$outfile->print( $line );
}
$infile->close();