Friday, January 25, 2013

Lua implementation of Aho-Corasick string matching

The Aho-Corasick string matching algorithm is a fast way of matching a large number of strings against  a source document. It consists of two stages: building of a special suffix tree and then matching against the tree. The algorithm is linear in the size of the source document (and number of matches) and matches all strings in the dictionary simultaneously and outputs them.

It is particularly helpful when a large dictionary of strings needs to be matched against a document. For example, it can be used to match a dictionary of known virus signatures against a suspicious executable. And it's possible to build the suffix tree ahead of time when the dictionary is fixed.

I needed a Lua implementation of the algorithm for a project and have created one (with a test suite) and released it here. There are two functions: build (which takes an array of strings, the dictionary, and returns the tree in the form of a Lua table) and match (which finds matches in a string given a tree). Since the tree is just a Lua table is can be serialized and loaded into programs as needed.

Lua 5.2.0  Copyright (C) 1994-2011, PUC-Rio
> AC = require 'aho-corasick'
> t ={"The", "han", "and", "pork", "port", "pot", "ha", "e"})
> m = AC.match("The pot had a handle")
> print(table.concat(m, ","))

The Wikipedia article has a good explanation of the algorithm itself, but to ease (my own) understanding of the algorithm in action I built a small Processing program that animates the process of matching. (The video is much easier to watch if seen on YouTube).

There's a small test suite included with the implementation. To run it do lua test.lua.

No comments: