CSV文件 - 如何使用Perl中的regexp限制字段长度

时间:2015-08-04 09:28:57

标签: regex perl csv text-parsing

我正在解析分号分隔的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 个答案:

答案 0 :(得分:3)

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

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

使用替换$3

[Regex Demo]

答案 1 :(得分:2)

它是否需要作为正则表达式完成?我想我会在您的split行中添加地图并使用substr

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

这对我来说更难维持。

答案 2 :(得分:1)

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