Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Longest String Matching

by kcott (Chancellor)
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]
[Discipulus]: thanks vrk i'll look at that site: but I exist just on perlmonks ;=)

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2017-04-27 08:17 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (501 votes). Check out past polls.