vivek
vivek

Reputation: 81

comparing two strings using perl regular expression

How to compare two unequal pattern and get the position for the following:

pat 1 : <start>\d+.\d+/\w+\_\w+<end>
pat 2 : <start>\d+.pe/rl/\w+vivek\w+<end>

i want output as

<starttag>\d+.<NOT>pe/rl</NOT>/\w+<NOT>vivek</NOT>\w+<endtag>

Thanks for the help in advance.

Upvotes: 2

Views: 712

Answers (1)

ysth
ysth

Reputation: 98388

It sounds like you want the output to have everything that is in both patterns, plus, in NOT tags, anything that is just in the second pattern? Your examples are slightly different than that (e.g. starttag instead of start, <startvivek> instead of <start>vivek). But assuming I'm right:

use strict;
use warnings;
use Algorithm::Diff;

my $one = '<start>\d+.\d+/\w+\_\w+<end>';
my $two = '<start>\d+.pe/rl/\w+vivek\w+<end>';
my $diff = Algorithm::Diff->new( [ split //, $one ], [ split //, $two ] );
my $combined = '';
while ( $diff->Next() ) {
    if ( $diff->Same() ) {
        $combined .= join '', $diff->Same();
    }
    elsif ( $diff->Items(2) ) {
        $combined .= join '', '<NOT>', $diff->Items(2), '</NOT>';
    }
}
print "$combined\n";

This outputs:

<start>\d+.<NOT>pe</NOT>/<NOT>rl/</NOT>\w+<NOT>vivek</NOT>\w+<end>

since it chooses to consider the / in the first pattern to match the first / in the second pattern instead of the second /.

Upvotes: 1

Related Questions