1

単語が2つしかない行に正規表現を適用したいと思います。私のファイルは次のようになり、括弧内の単語の間に可変数のスペースがあります。

Politician_name :(ホセマリアアズナール|ホセマリアアズナール|ホセマリアアズナール|ホセマリアアズナール); Politician_name :(トニーブレア|トニーブレア|トニーブレア|トニーブレア);

出力として欲しい:

Politician_name :(トニーブレア|トニーブレア|トニーブレア|トニーブレア|ブレアトニー|ブレアトニー);

私のコードは各行に正規表現を適用し、次のような誤った出力を受け取ります。

Politician_name :(ホセマリアアズナール|ホセマリアアズナール|ホセマリアアズナール|ホセマリアアズナール|マリアホセ|マリアホセ);

これは私のコードです:

use strict;
use warnings;
use Data::Dumper;
use utf8;

open(IN, $ARGV[0]) or die "Can't read file $ARGV[0]\n";
while (my $line=<IN>)
{
    my ($pol,$value) = split(/:/, $line);

    warn Dumper \$pol;
    chomp($value);
    $value=~ s/[  ]+/ /g;
    $value=~ s/\);//g;
    my $n;  
    $n = $1 if ($value =~ /\((.+?)\|/); 
    $n=~ m/(\w*)\s(\w*)/g;
    my $swapname="$2 $1";
    warn Dumper \$swapname;

    print "$pol: $value | $swapname );\n";

}
close(IN); 

3語の名前の処理を停止するにはどうすればよいですか?

4

1 に答える 1

2
$n=~ m/(\w*)\s(\w*)/g;   # Replace this regex with the one below

以下の正規表現を使用して比較し$nます。また、それをで囲む必要があります。そうでない場合if、すべての入力に対して印刷が実行されます。

my $n;  
$n = $1 if ($value =~ /\((.+?)\|/); 
if ($n =~ m/^\s*(\w+)\s(\w+)\s*$/g) {  # Notice `$` to mark the end of 2 words..
    my $swapname="$2 $1";
    warn Dumper \$swapname;

    print "$pol: $value | $swapname );\n";
}

しかし、あなたは次の値を考慮に入れていません|..あなたはそれをする必要があります..それはただ最初の値を取っているだけです..

したがって、出力は次のようになります。

Politician_name: (Tony Blair |tony blair | Tony Blair | tony blair | Blair Tony )

2番目tony blairは使用されていません。そのためのコードを変更する必要があります。


実際には、このコードを正しく機能させるために、すべての名前を反復処理するためのループが必要です。


更新:-私はむしろあなたのコードを次のように変更したいと思います:-

# You should always use lexical variables as file handles..
open my $fh, '<', 'D:\demo.txt' or die $!;

while (<$fh>)  # Don't need use any extra variable here.. Default to $_
{
    my ($pol,$value) = split /:/;  # Do split on $_ by default
    warn Dumper \$pol;

    chomp($value);

    $value=~ s/[  ]+/ /g;
    $value=~ s/\((.*)\);/$1/g;

    my @name = split(/\|/, $value);  # Split your string to an array

    # Filter out array to remove duplicate

    my $_ = $name[0]; 

    if (m/^\s*(\w+)\s(\w+)\s*$/g) {  

        # If first element contains 2 words, proceed with rest of the elements

        print "($value ";  # print the original string you want..

        # Append to it later on the reverse of other array elements

        foreach (@name) {
            if (m/^\s*(\w+)\s(\w+)\s*$/g) {

                my $swapname = "$2 $1";
                warn Dumper \$swapname;

                print "| $swapname ";  # Print swapnames after $value
            }
        }
        print ");\n";  # End the string..
    }
}
close($fh);
于 2012-10-11T10:58:53.877 に答える