如何搜索由空格分隔的特定单词索引?在Perl Regex中

时间:2012-11-11 12:14:01

标签: regex perl field extraction

我有一个像

这样的日志文件

field1 field2 field3 field4withvariablelength ... field5with ...

有没有办法使用perl正则表达式提取例如字段5,比如

“用空格分隔”和“给我索引5”??

2 个答案:

答案 0 :(得分:5)

当然,您可以使用split按空格分隔:

my (@fields) = split /\s+/;
print $fields[4];

这是一个完整的测试脚本:

#!/usr/bin/perl -w
use strict;

while (<DATA>) {
    my (@fields) = split /\s+/;
    print $fields[4];
}    


__DATA__
field1 field2 field3 field4withvariablelength... field5with...

答案 1 :(得分:0)

或者像这样:

my $str = "field1 field2 field3 field4withvariablelength ... field5with...";
$str =~ m/field5(.*)$/i;
print $1; # type with...

如果你有其他领域:

$str =~ m/\s+field4(.*)\s+/i;
print $1; # type withvariable...
相关问题