【问题标题】:how to search for a specific word index delimited by a space ? in Perl Regex如何搜索由空格分隔的特定单词索引?在 Perl 正则表达式中
【发布时间】:2012-11-11 12:14:01
【问题描述】:

我有一个类似的日志文件

field1 field2 field3 field4withvariablelength ... field5with...

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

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

【问题讨论】:

    标签: regex perl field extraction


    【解决方案1】:

    当然可以,你可以用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...
    

    【讨论】:

      【解决方案2】:

      或者像这样:

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

      【讨论】:

      • 这不是提问者想要的。他想要的是这样的:"Delimit with spaces" and "Give me index 5"
      • 哦,那我理解错了
      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      相关资源
      最近更新 更多