【问题标题】:comparing two string by adding pattern in perl通过在 perl 中添加模式来比较两个字符串
【发布时间】:2014-03-17 16:58:34
【问题描述】:

我想匹配两个字符串,然后在最终输出中附加一些标签 例如

$string1 = “Adaptive Actuator Failure and Structural <match>Damage</ match > Compensation of NASA”;

$string2 = “Adaptive Actuator Failure <?show $262#?>and Structural Damage <?show $262#?>Compensation of NASA”;

需要输出:

“Adaptive Actuator Failure <?show $262#?>and Structural <match>Damage</match> <?show $262#?>Compensation of NASA”

解释:我想将数据从 string1 映射到 string2,但问题在于 string2 有附加元素。这些元素可以出现在 string2 中的任何位置。

注意:我们不能从 string2 中删除标签,因为我们希望它保留在最终输出中

我尝试为每个字母添加元素模式,但它不起作用。

我试过的代码:

$each = "(?:(?:\\s*<[\\#\\s\\\$\\w\\=\\-\\\"\\/\\?]+>\\s*)+)?".$each."(?:(?:\\s*<[\\#\\s\\$\\w\\=\\-\\\"\\/\\?]+>\\s*)+)?";

变量 $each 包含每个字母、符号或空格。

还有其他逻辑吗??

【问题讨论】:

  • 我不确定我是否理解这些要求。你配什么?你在添加什么?它与比赛有什么关系?我之所以这样问,是因为有可能以更简单的方式来表述问题——因此以更简单的方式解决它:广义解析而不是模式匹配。

标签: regex perl


【解决方案1】:

您可以通过这种方式使用正则表达式。请注意,它不会太健壮,它只适用于相对健全的输入。

use strict;use warnings;
my $string1 = “Adaptive Actuator Failure and Structural <match>Damage</ match > Compensation of NASA”;

my $string2 = “Adaptive Actuator Failure <?show $262#?>and Structural Damage <?show $262#?>Compensation of NASA”;

#search string 1
my $se1 = $string1;
my $se2 = $string2;
#remove all tags
$se1 =~ s!<[^>]*>!!gis;
$se2 =~ s!<[^>]*>!!gis;
#normalize spaces
$se1 =~ s!\s+! !gis;
$se2 =~ s!\s+! !gis;
#found a match
if ($se1 eq $se2){
  #found each tag is s1
  my $s = $string1;
  while ( $s =~ s!(<[^>]*>)(.+?)(</\s*[^>]*>)!!is){
     my $begin_tag = $1;my $end_tag = $3;my $text = $2;
     ### replace the text in the s2 with tagged
     $string2 =~ s!$text!$begin_tag$text $end_tag!is;

  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2015-06-17
    • 1970-01-01
    • 2012-03-23
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多