Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Longest String Matching

by kcott (Bishop)
on Apr 08, 2013 at 12:14 UTC ( #1027482=note: print w/replies, xml ) Need Help??

in reply to Longest String Matching

G'day Dr Manhattan,

I think you decided that splitting the word into individual characters was a good approach and then got rather bogged down attempting to wring a solution from this technique. A regex using alternation would probably be a better way to do this.

$ perl -Mstrict -Mwarnings -E ' my %lexicon = map { $_ => 1 } qw{own known}; my $string = q{unknown}; my $alt = join q{|} => sort { length $b <=> length $a } keys %lexi +con; my $re = qr{ ( (?> $alt ) ) $ }x; $string =~ $re; say $1; ' known

Also, unless the hash %lexicon already exists for some other purpose, you'd probably be better off with an array:

$ perl -Mstrict -Mwarnings -E ' my @lexicon = qw{own known}; my $string = q{unknown}; my $alt = join q{|} => sort { length $b <=> length $a } @lexicon; my $re = qr{ ( (?> $alt ) ) $ }x; $string =~ $re; say $1; ' known

Note how sort puts the longest string first, i.e. to test for "known" before testing for "own". See perlreftut for an introduction to alternation; and perlre for more information as well as a description of the (?>pattern) construct (in the Extended Patterns section).

-- Ken

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1027482]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2020-09-30 09:10 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (160 votes). Check out past polls.