首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Perl如何仅对有两个单词的变量应用regex?

Perl如何仅对有两个单词的变量应用regex?
EN

Stack Overflow用户
提问于 2012-10-11 10:31:37
回答 1查看 175关注 0票数 1

我想在只有两个单词的行上应用正则表达式。我的文件在括号中的单词之间有可变的空格数,如下所示:

Politician_name:(何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔);Politician_name:(托尼·布莱尔、托尼·布莱尔·托尼·布莱尔·托尼·布莱尔);

我想要一个输出:

Politician_name:(托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·托尼,);

我的代码将正则表达式应用于每一行,并得到如下错误输出:

Politician_name:(何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔玛丽亚·何塞·何塞·何塞 );

这是我的密码:

代码语言:javascript
复制
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); 

我该怎么做才能停止处理三个字的名字?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-11 10:58:53

代码语言:javascript
复制
$n=~ m/(\w*)\s(\w*)/g;   # Replace this regex with the one below

使用下面的Regex与$n进行比较,还需要将其包含在一个if中,其他明智的方法是对每个输入执行打印:-

代码语言:javascript
复制
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";
}

但是,您没有考虑|之后的下一个值。你得这么做..。它只是取第一个值..。

因此,您的输出将是:-

代码语言:javascript
复制
Politician_name: (Tony Blair |tony blair | Tony Blair | tony blair | Blair Tony )

第二tony blair没有被使用。您需要为此修改代码。

实际上,您需要一个循环来迭代每个名称,以使这段代码正常工作。

UPDATE :- 我宁愿将您的代码更改为:-

代码语言:javascript
复制
# 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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12837561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档