【问题标题】:regular expression to remove white spaces in a line and extract specific columns正则表达式删除一行中的空格并提取特定列
【发布时间】:2012-10-10 05:26:09
【问题描述】:

Perl 正则表达式删除一行中的空格并提取特定列

我的线是这样的:

324446  psharma jobA      2       0       435529  0       0       0     435531

在这里我可以使用split 函数拆分行,然后使用以下命令将值保存在数组中

@strings = split(/\s+/);

我不想要一个额外的变量。 使用正则表达式,我想将第 1、2、3 和 10 列中的值提取为 $1$2$3$10

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    欢迎来到 stackexchange。

    不需要额外的变量:

    use strict;
    use warnings;
    
    my $line = '  324446   psharma jobA 2   0 435529 0 0 0 435531     ';
    
    # Remove leading and trailing white space
    $line =~ s/^ \s+ | \s+ $//x;
    # Split by consecutive white space and keep certain fields:
    my ($col1, $col2, $col3, $col10) = (split m/\s+/, $line)[0, 1, 2, 9];
    
    print "1: $col1 2: $col2 3: $col3 10: $col10\n";
    

    输出:

    1: 324446 2: psharma 3: jobA 10: 435531
    

    意味着你真的不需要任何额外的变量,即使是split。例如,如果您只想将这些字段传递给另一个函数,您的分割线将如下所示:

    some_func((split m/\s+/, $line)[0, 1, 2, 9]);
    

    请注意,我假设您的列号计数从 1 开始,而不是从 0 开始(意味着您的“第 1 列”是数字“324446”等)。这也是我在示例中命名变量的方式。

    【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2020-10-27
    • 1970-01-01
    • 2021-11-17
    • 2016-06-17
    • 2011-11-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多