代码之家  ›  专栏  ›  技术社区  ›  taiko

CSV文件-如何在Perl中使用正则表达式限制字段长度

  •  0
  • taiko  · 技术社区  · 9 年前

    我正在解析一个分号分隔的CSV文件,其中的行如下

    firstField;secondField;thirdField;fourth very long field which I need to truncate;fifth very long field which I need to truncate"
    

    我需要将所有字段截断为10个字符

    我可以一个字段一个字段地截断它,如

    open my $input, "<", "inputFile.txt" or die "Can't open the inputFile.txt";
    while (my $line = <$input>){
         chomp($line);
         my @fields = split(';',$line);
         for $field (@fields){
             $field =~ s/.{10}\K.*// if ((defined $field) && (length $field > 10));
             }
         }
    

    有没有任何方法可以使用正则表达式来实现这一点? 类似的东西

    $line = s/;.{10}\K.*;?//g
    
    3 回复  |  直到 9 年前
        1
  •  3
  •   shA.t Rami Jamleh    7 年前

    我想你可以使用这样的正则表达式:

    /(^|;)(([^;]{1,10})([^;]*))/g
    

    有替代品 $3 .

    [Regex Demo]

        2
  •  2
  •   Dave Cross    9 年前

    是否需要作为正则表达式执行?我想我会在你的 split 线路和使用 substr .

    my @fields = 
      map { length > 10 ? substr($_, 0, 10) : $_ }
      split(/;/,$line);
    

    这对我来说更容易维护。

        3
  •  1
  •   user557597 user557597    9 年前

    这不应该这么复杂。使用Perl和
    仅删除超过10个字符的内容。不需要像{1,10}这样的范围。

    快速插入整个文件,对整个文件进行替换。
    让生活更轻松。

    $csv_str =~ s/(?m)(?:^|;)[^;\n]{10}\K[^;\n]+//g;

     (?m)           # Multi-line mode
     (?: ^ | ; )    # BOL (beginning of line) or semi-colon
     [^;\n]{10}     # 10 chars, not semi-colon nor linebreak
     \K             # Clear the match buffer of all previous data
     [^;\n]+        # This is to be gotten rid of...
                    # 1 or more not semi-colon nor linebreak
                    # On to the next match
    

    比赛:

     **  Grp 0 -  ( pos 21 , len 1 ) 
    d  
    
    -----------------------
    
     **  Grp 0 -  ( pos 44 , len 37 ) 
    y long field which I need to truncate  
    
    -----------------------
    
     **  Grp 0 -  ( pos 92 , len 37 ) 
     long field which I need to truncate"