簡體   English   中英

Perl正則表達式模式

[英]Perl Regular Expression Pattern

我有這樣一些數據:

TYPE: Travel
ADDRESS
  Barcelona
  Paris

因此,地址可以是1或很多(我需要丟棄ADDRESS並僅獲取那些城市)。 由於某些原因,我的解析失敗(僅打印“ ADDRESS”)無法產生正確的結果。我錯過了什么嗎?

elsif (/^ADDRESS/) {
    my @address_t = split /[no matter what i put,only ADDRESS is printed]+/, $_;
        shift @address_t;  #is this how i will discard ADDRESS ?

        foreach my $address (@address_t) {
                @address_names = ($address);            
    }

我認為正則表達式應該被換行,空格?

這就是我處理TYPE的方式:

elsif (/^TYPE/) {
            my @type_t = split '\s', $_;
            $type = $type_tmp[1];
                    print "$type" ; #to test, but i have a hashmap which i load them in and print at the end of the file.

謝謝

嘗試這樣的事情:

如果前一行匹配/^ADDRESS/ ,它將打印行。 讓我知道您是否要停止,我可以調整...

use warnings;
use strict; 

my $current_line = "";
my $line_count = 0;

while (<IN>){
    chomp;
    my $previous_line = $current_line;
    $current_line = $_;
    if ($previous_line =~ /^ADDRESS/ or $line_count > 0 ){
    $line_count++;
    print "$current_line\n"

    }   
}
use warnings;
use strict;

while(<DATA>) {
    if (/^ADDRESS/) {           # if line contains ADDRESS then read addresses
        while (<DATA>) {        # ... in a loop
            last if !/^ +/;     # until we find a non-indented line
            print $_;           # here you can push $_ to a list
        }
    }   
    if ($_ && /^TYPE/) {        # a TYPE after address can be processed now
        # stuff 
    }   
}

__DATA__
TYPE: Travel
ADDRESS
  Barcelona
  Paris
TYPE: Travel
ADDRESS
  Barcelona
  Paris

生產:

  Barcelona
  Paris
  Barcelona
  Paris

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM