使用哈希进行条件替换

时间:2014-04-21 05:04:48

标签: perl hash substitution

我试图替换条件允许或禁止替换。 我有一个字符串

$string = "There is <tag1>you can do for it. that dosen't mean <tag2>you are fool.There <tag3>you got it.";

这是两个用于检查条件的哈希值。

my %tag = ('tag1' => '<you>', 'tag2'=>'<do>', 'tag3'=>'<no>');
my %data = ('you'=>'<you>');

这是实际替换,其中允许替换不匹配的哈希标记值。

$string =~ s{(?<=<(.*?)>)(you)}{
    if($tag{"$1"} eq $data{"$2"}){next;}
    "I"
}sixe;

在此代码中,我想替换&#39;条件不符合标签中给出的哈希值的条件。
我可以使用next代替吗? 问题是我不能使用\ g修饰符。使用next后,我无法进行下一次替换。 此外,我无法在匹配时修改表达式,并使用下一个它进行第二场比赛,它会停在那里。

2 个答案:

答案 0 :(得分:1)

你不能在断言后面使用可变长度的外观。唯一允许的是特殊\K标记。

考虑到这一点,执行此测试的一种方法如下:

use strict;
use warnings;

while (my $string = <DATA>) {
    $string =~ s{<([^>]*)>\K(?!\1)\w+}{I}s;
    print $string;
}

__DATA__
There is <you>you can do for it. that dosen't mean <notyou>you are fool.
There is <you>you can do for it. that dosen't mean <do>you are fool.There <no>you got it.

输出:

There is <you>you can do for it. that dosen't mean <notyou>I are fool.
There is <you>you can do for it. that dosen't mean <do>I are fool.There <no>you got it.

答案 1 :(得分:0)

这很简单,但我有两天时间考虑它。我刚写了另一个替换,它忽略了由next;

取消的前一个标记
$string = "There is <tag1>you can do for it. that dosen't mean <tag2>you are fool.There <tag3>you got it.";


my %tag = ('tag1' => '<you>', 'tag2'=>'<do>', 'tag3'=>'<no>');
my %data = ('you'=>'<you>');

my $notag;

$string =~ s{(?<=<(.*?)>)(you)}{
    $notag = $2;
    if($tag{"$1"} eq $data{"$2"}){next;}
    "I"
}sie;

$string =~ s{(?<=<(.*?)>)(?<!$notag)(you)}{
   "I"
}sie;
相关问题