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

Re: Matching bits of 2 strings

by japhy (Canon)
on Jan 22, 2002 at 04:50 UTC ( #140550=note: print w/ replies, xml ) Need Help??


in reply to Matching bits of 2 strings

This is the "leading common substring" problem. There's been work in Perl done on it. Here's a relatively fast solution:

# leading common substring # returns length of LCS # requires Perl 5.6+ sub lcs { ($_[0] ^ $_[1]) =~ /\0*/; return $+[0]; }
If you're not fortunate enough to have Perl 5.6 yet, here's a compatible approach:
# leading common substring # returns length of LCS # requires Perl 5.6+ sub lcs { ($_[0] ^ $_[1]) =~ /(\0*)/; return length $1; }
Update: in case you were worried, I do not need a ^ anchor in these regexes, because * will gladly match zero times at the beginning of the string if it has to.

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;


Comment on Re: Matching bits of 2 strings
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2014-08-02 02:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (53 votes), past polls