【问题标题】:Perl Regular Expression QuestionPerl 正则表达式问题
【发布时间】:2011-03-05 12:10:42
【问题描述】:

我写了一个 Perl 程序,它从文本文件中读取文本并打印出来。

我想打印出具有特定格式的行。

例如,有一些这样的行:

information:
Ahmad.prn:592118:2001:7:5:/Essay
Ashford.rtf:903615:2001:6:28:/usr/Essay
Barger.doc:243200:2001:7:4:/home/dir
end of Information.

我只想读这三行:

Ahmad.prn:592118:2001:7:5:/Essay
Ashford.rtf:903615:2001:6:28:/usr/Essay
Barger.doc:243200:2001:7:4:/home/dir

我认为字段的含义是:

Ahmad.prn <- file name
592118 <- size of file
2001:7:5 <- created date
/Essay <- path of file

我的代码是这样的:

#!/usr/bin/perl
use strict;
use warnings;

open (my $infh, "<", $file)||die "cant open";

while(my $line = <$infh>) {
    chomp ($line);
    if ($line =~ /(what regular expression do I have to put in here?)/) {
        print "$line";
    }
}

close ($infh);

【问题讨论】:

  • 您确实需要提供更多关于您要实现的目标的信息。
  • 请清楚说明行格式是什么。目前尚不清楚您是否只想删除第一行和最后一行,仅匹配以 /Essay 结尾的行,匹配匹配 a:b:c:d:e:f ....的行。

标签: regex perl


【解决方案1】:

如果你需要的行总是以 /Essay 结尾,你可以使用下面的正则表达式

/:\/Essay$/

编辑1:看起来中间部分只有数字,你可以这样匹配。

/:\d+:\d+:\d+:\d+:/

【讨论】:

  • 我认为符号是 'filename:filesize:date:path' em.. '~'
  • @misaka,所以,中间部分只有数字吗?添加了另一个正则表达式
  • @misaka,你是说分裂吗? split(/:/, $line); 将返回 6 个项目数组
  • Ahmad.prn:592118:2001:7:5:/Essay 我想将 2001:7:5 绑定为一个值......但如果我使用上面的拆分代码,我想我不能......
  • @misaka,在这种情况下,您可以像这样拆分 /([^:]+):(\d+):(\d+:\d+:\d+):(.+)/,或者使用匹配方法 m// 而不是拆分 // 更好。
【解决方案2】:

因为您有 Ahmad.prn:592118:2001:7:5:/Essay 的这种格式

Ahmad.prn <- file name
592118 <- size of file
2001:7:5 <- created date
/Essay <- path of file

你可以使用这个正则表达式

/^\s*(\S+):(\d+):(\d+:\d+:\d+):(\S+)\s*$/

有了这个,你将有 $1 中的文件名,$2 中的文件大小,$3 中的创建日期,$4 中的文件路径

我在行首和行尾添加了可选空格,如果你想在之后或之前允许可选空格:你可以添加 \s*

【讨论】:

    【解决方案3】:
    #!/usr/bin/perl
    use strict;
    
    my $inputText = qq{
    Ahmad.prn:592118:2001:7:5:/Essay
    Ashford.rtf:903615:2001:6:28:/usr/Essay
    Barger.doc:243200:2001:7:4:/home/dir
    end of Information.
    };
    
    my @input = split /\n/, $inputText;
    my $i = 0;
    while ($input[$i] !~ /^end of Information.$/) {
        if ($input[$i] !~ /:/) {
            $i++;
            next;
        }
        my ($fileName, $fileSize, $year, $month, $day, $filePath) = split /:/, $input[$i];
        print "$fileName\t $fileSize\t $month/$day/$year\t $filePath\n";
        $i++;
    }
    

    【讨论】:

      【解决方案4】:
      $line =~ ([a-zA-Z.]+):(\d+):(\d+):(\d+):(\d+):([\/A-Za-z]+)
      
      $name = $1; #Ahmad.prn
      $id = $2; #592118
      $year = $3; #2001
      $dir = $6; #/Essay 
      

      注意:循环遍历多个名称

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多