regex - Perl:从当前位置替换模式直到行尾

标签 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.

最佳答案

我看到你已经接受了一个答案。但是,对于手头的任务,使用 Apache::ParseLog 会更合适。或者也许 Apache::LogRegex :

Apache::LogRegex - Parse a line from an Apache logfile into a hash

在我看来,您正在尝试从头开始编写日志文件分析器,这是您按月对日志文件条目进行分组的方式。如果是这样,请停止重新发明方轮。

即使您不想使用外部模块,您也可以通过使用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";

输出:

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+(兼容;+MSIE+5.0;+Windows+98 ;+DigExt;+Hotbar+2.0)"

关于regex - Perl:从当前位置替换模式直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1737413/

相关文章:

javascript - 正则表达式的替代方案 $1 进行替换

c# - 匹配 html 标签之外的文本

windows - 您如何构建针对 Windows 的 perl 源代码?

perl - 使用 LWP::UserAgent 损坏图像

python - 在 for 循环中使用 str.replace 将非字母数字字符替换为星号

javascript - 如何编写 Regex 来替换一些单词并在 JavaScript 中缺少时添加 ""。意外行为

regex - First Re 不能为空

java - 将倒数计时器转换为时间的正则表达式

不相等的 Perl if 语句

c - 在 C 中替换字符串中的字符并随后取消替换的最佳方法