0

假设,我有 2 个字符串。

$file1_out="astra.abs ::nerve :  Costa.br_.cotAlev.ksaf.large.props.fault_check"
$file2_out="astra.abs ::nerve :  Costa.br_.cotBlev.ksaf.large.props.fault_check"

您可以看到,唯一的区别是 cotAlev 和 cotBlev 中的 2 个字符串中的 A 和 B。我想比较它们并获得 2 个新变量

$part1="astra.abs ::nerve :  Costa.br_."
$part2=".ksaf.large.props.fault_check"
$var="cot_lev" ###removed the mismatching character

这是中断直到第一个不相等的单词并分成 3。我怎么能做到这一点在 PERL 中使用正则表达式

我是 perl 的新手,在这里使用 C 中常见的循环概念来解决这个问题。我通过将字符串分解为字符来比较每个字符,然后将它们相应地组合成 3 个变量来实现这一点。但有人告诉我有更简单的方法可以做到这一点。有很多比较要做,所以速度确实很重要......

4

2 回答 2

1

看看Text::Diff,它可能会做你已经尝试做的事情。

于 2013-10-04T15:29:28.357 回答
1

我不确定如何使用正则表达式来处理。你说你用C循环处理这个。你可以在 Perl 中做类似的事情。

my @file1_chars = split //, $file1_out;
my @file2_chars = split //, $file2_out;

这会将您的字符串拆分为一个数组,数组中的每个条目都是一个单独的字符。现在你可以循环直到你找到你的第一个不匹配的字符:

my $first_mismatched;
for my $char_num ( (0..$#file1_chars) ) {
    if ( $file1_chars[$char_num] ne $file2_chars[$char_num] ) {
        $first_mismatched = $char_num;
    }
}
if ( defined $first_mismatched ) {
    say "The two strings stop matching on character # $first_mismatched";
}

这将打印出:

The two strings stop matching on character # 34

是的$#file1_chars最后一个数组索引@file1_chars。从 的第(0..$#file1_chars)一个索引条目到最后一个索引条目的索引@file1_chars

您可以将其反转以从最后一个字符转到第一个字符:

my $last_mismatched;
for my $char_num ( reverse (0..$#file1_chars) ) {
    if ( $file1_chars[$char_num] ne $file2_chars[$char_num] ) {
        $last_mismatched = $char_num;
    }
}
if ( defined $last_mismatched ) {
    say "The two strings restart matching on character # $first_mismatched";
}
于 2013-10-04T15:38:59.083 回答