String-matching-algorithm May 30, 2007 at 4:44 pm

Need to find specific textsnippets within text? Ever heard of the Boyer-Moore-Algorithm?

At the beginning, the pattern will be written left aligned under the text and then compared from right to left with it. Once a mismatch is found, two heuristics calculate how far to the right the searchpattern can be displaced.

function bm(txt, pattern){

var tlen:Number = txt.length;
var mlen:Number = pattern.length;
var i:int;
var j:int;
var match:Array = new Array(256);

for(i=0; i<256; ++i) match[i] = mlen;
for(i=0; i

for(i=j=mlen-1; j>0; –i, –j)
while(txt.charAt(i) != pattern.charAt(j)) {
if (match[txt.charAt(i)] != undefined) {
i += Math.max(mlen-j,match[txt.charAt(i)]);
} else {
i++;
}
if(i >= tlen) return -1;
j = mlen-1;
}
return “searchstring matches between ” + i + ” ” + (i+mlen);
}

trace(bm(”climb that mountain to cut off the top”, “mo”));

One Response to “String-matching-algorithm”

  1. […] boyer Moore algorithm: http://redbrain.co.uk/?p=157 … Mail (will not be published) (required) …actionscript microcosmos String-matching-algorithmEver heard of the Boyer-Moore-Algorithm? At the beginning, the pattern will be written left aligned […]

Leave a Reply