【问题标题】:Identifying Difference in string using Perl使用 Perl 识别字符串中的差异
【发布时间】:2014-09-10 22:23:14
【问题描述】:

我有 2 个字符串(句子),我想找出两个字符串(句子)不匹配时的具体差异。

我的示例代码如下

my $diffpara1 = "This is paragraph 1";

my $diffpara2 = "This is paragraph 2 different from first paragraph";

my $samepara1 = "This is paragraph is same";

my $samepara2 = "This is paragraph is same";

print (($diffpara1 eq $diffpara2) ? '<span style="background-color: green">Matching</span>' : '<span style="background-color: red">Not Matching</span>');

print "<br/>".(($samepara1 eq $samepara2) ? '<span style="background-color: green">Matching</span>' : '<span style="background-color: red">Not Matching</span>');

以上代码的结果是:

以上仅表示字符串(句子)是否匹配或字符串(句子)不匹配。但我想生成一个输出,表明两个字符串(句子)的不同之处。

我想要的示例输出(BOLD 区别):

这是第 1 段
这是第 第 2 段与第一段不同 段落

我不确定我们是否可以使用 REGEX 来获得所需的输出。

提前感谢您的帮助。

【问题讨论】:

  • This is textThis is word 应该打印什么?
  • 与其重新发明轮子,还有一些 Perl 模块已经这样做了——你搜索过 CPAN 吗?我过去使用过 Text::WordDiff:metacpan.org/pod/Text::WordDiff
  • 感谢@ialarmedalien 我尝试了Text::WordDiff 模块,它成功了。正是我想要的。

标签: regex string perl difference


【解决方案1】:

试试Text::WordDiff。您可以将差异输出为 HTML,删除和插入的部分分别用 &lt;del&gt;&lt;ins&gt; 标签标记。一个简单的例子:

use strict;
use warnings;
use feature ":5.10";
use Text::WordDiff;

my $diffpara1 = "This is paragraph 1";
my $diffpara2 = "This is paragraph 2 different from first paragraph";

# output the difference between the lines as HTML, on two lines:
my $diff = word_diff \$diffpara1, \$diffpara2, { STYLE => 'HTMLTwoLines' };

say $diff;

输出:

<div class="file"><span class="hunk">This is paragraph </span><span class="hunk"><del>1</del></span></div>
<div class="file"><span class="hunk">This is paragraph </span><span class="hunk"><ins>2 different from first paragraph</ins></span></div>

相同的行:

my $samepara1 = "This is paragraph is same";
my $samepara2 = "This is paragraph is same";
my $diff2 = word_diff \$samepara1, \$samepara2, { STYLE => 'HTMLTwoLines' };
say $diff2;

输出:

<div class="file"><span class="hunk">This is paragraph is same</span></div>
<div class="file"><span class="hunk">This is paragraph is same</span></div>

有许多不同的输出选项(另存为纯文本、另存为 html、保存到文件、保存到变量等),您可以轻松配置 html 版本,以不同的方式显示插入和删除的文本颜色,粗体,或者使用 css 的强大功能。

【讨论】:

  • 感谢@ialarmedalien,我尝试了上面的示例,并且成功了。
猜你喜欢
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2010-10-02
  • 1970-01-01
相关资源
最近更新 更多