【问题标题】:How to start matching and saving matched from exact point in a text如何从文本中的确切点开始匹配和保存匹配
【发布时间】:2011-01-13 00:50:57
【问题描述】:

我有一个文本,我使用正则表达式和 perl 为它编写了一个解析器。

我可以用两个空行匹配我需要的内容(我使用正则表达式),因为有一种模式可以识别两个空行之后的文本块。

但问题是全文有引言部分,最后有些文字我不需要。

这是一个找到两个空行时匹配文本的代码

#!/usr/bin/perl

use strict;
use warnings;

my $file = 'first';                    
open(my $fh, '<', $file);   
my $empty = 0;    
my $block_num = 1;    
open(OUT, '>', $block_num . '.txt');    

while (my $line = <$fh>) {  

 chomp ($line);
 if ($line =~ /^\s*$/) {  
  $empty++;      
  } elsif ($empty == 2) {     
   close(OUT);    
   open(OUT, '>', ++$block_num . '.txt');
   $empty = 0;
  } 
  else {
   $empty = 0;}
 print OUT "$line\n";

}
close(OUT);

这是我需要的文本示例(真的很小:))


this is file example


我认为我需要遍历文本直到它找到带有正则表达式“/^LOREM IPSUM/”的单词 LOREM IPSUM,因为它是所需文本的开始点(并保存文本当我到达这个词时,在一个文件中)。 我需要在找到 INDEX 单词时完成对文本的迭代或将文本保存在单独的文件中。

我该如何实现它。我应该使用 next 函数来处理线条还是什么?

BR, 玉莉娅

【问题讨论】:

  • 我会吞下文件并匹配块。这样你就不必搞乱有点难看的行数
  • 也许你是对的,但我更愿意用一些代码来做

标签: regex perl matching


【解决方案1】:

您可以将 while 循环更改为类似

my $in_lorem = 0;
while (my $line = <$fh>) {
  if( $line =~ /^LOREM IPSUM/ ) {
    $in_lorem = 1;
    next;
  }
  next unless $in_lorem;
  # your processing goes here
}

这将跳过标题行,直到您点击以LOREM IPSUM 开头的行,之后您将处理行。

您可以使用类似的模式来忽略给定行匹配后的所有行,除非您不必处理更多行,因此您可以使用last 而不是使用next。该模式留给读者作为练习。 :-)

【讨论】:

    【解决方案2】:

    您可以使用flip flop range operator 在匹配 LOREM IPSUM 时开始处理,并在匹配 INDEX 时停止处理。

    #!/usr/bin/perl
    use strict;
    use warnings;
    use 5.010;
    
    my $file = 'firsttest';
    
    open (my $fh, '<', $file) or die "Failed to open $file: $!";
    
    while (<$fh>){
        if (m/^LOREM IPSUM/ .. m/^INDEX/){
            #Do your other matching, processing, etc. here
            print;
            last if m/^INDEX/;#Optional, to avoid reading remaining lines.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多