Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Longest String Matching

by kcott (Abbot)
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


Comment on Re: Longest String Matching
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (12)
As of 2014-09-30 19:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (381 votes), past polls