Perl:将模式从当前位置替换为一行

Luc*_*cia 2 regex perl replace

Perl中,如何将模式从当前位置(最后一次替换的位置)替换为一行?

我在一行中完成了所有这些替换:

...
s/\[//;
s/(\/\w\w\w\/)/ getMonth $1 /e;
s/:/ /;
s/\s\+\d\d\d\d\]//;
#NOW: replace all blanks with a plus sign from this position until the end of this line.
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 8

我看到你已经接受了答案.但是,对于手头的任务,使用Apache :: ParseLogApache :: LogRegex更合适:

Apache::LogRegex - 将Apache日志文件中的一行解析为哈希

在我看来,您正在尝试从头开始编写日志文件分析器,这是按月分组日志文件条目的方法.如果是这种情况,请停止重新发明方形车轮.

即使您不想使用外部模块,也可以通过使用split进行划分和征服来简化任务:

#!/usr/bin/perl

use strict; use warnings;
use Carp;
use Regex::PreSuf;

my @months = qw(jan feb mar apr may jun jul aug sep oct nov dec);
my %months = map { $months[$_] => sprintf '%02d', $_ + 1 } 0 .. 11;
my $months_re = presuf( @months );

# wrapped for formatting, does not make any difference
my $str = q{62.174.188.166 - - [01/Mar/2003:00:00:00 +0100] "GET
/puntos/img/ganar.gif HTTP/1.1" 200 1551
"http://www.universia.com/puntos/index.jsp";
"Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt; Hotbar 2.0)"};

chomp($str);

my @parts = split qr{\s\[|\]\s}, $str;

if ( $parts[1] =~ m! / ($months_re) / !ix ) {
    $parts[1] = $1;
}

$parts[2] =~ s/\s/+/g;

print join(' ', @parts), "\n";
Run Code Online (Sandbox Code Playgroud)

输出:

62.174.188.166 - - Mar "GET+/puntos/img/ganar.gif+HTTP/1.1"+200+1551+"http://www .universia.com/puntos/index.jsp";+"Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+98 ;+DigExt;+Hotbar+2.0)"