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

CSV file - how to limit fields length using regexp in Perl

我正在解析一个以分号分隔的 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

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

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

替换 </code>.</p> <p><a href="https://regex101.com/r/cB2fK7/2" rel="nofollow noreferrer"><strong><code>[Regex Demo]

是否需要作为正则表达式完成?我想我会在你的 split 行中放一张地图并使用 substr.

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

我觉得这更易于维护。

不应该这么复杂。使用 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"