Home

Awesome

ahocorasick_rs: Quickly search for multiple substrings at once

ahocorasick_rs allows you to search for multiple substrings ("patterns") in a given string ("haystack") using variations of the Aho-Corasick algorithm.

In particular, it's implemented as a wrapper of the Rust aho-corasick library, and provides a faster alternative to the pyahocorasick library.

Found any problems or have any questions? File an issue on the GitHub project.

Quickstart <a name="quickstart"></a>

The ahocorasick_rs library allows you to search for multiple strings ("patterns") within a haystack, or alternatively search multiple bytes. For example, let's install the library:

$ pip install ahocorasick-rs

Searching strings

We can construct a AhoCorasick object:

>>> import ahocorasick_rs
>>> patterns = ["hello", "world", "fish"]
>>> haystack = "this is my first hello world. hello!"
>>> ac = ahocorasick_rs.AhoCorasick(patterns)

You can construct a AhoCorasick object from any iterable (including generators), not just lists:

>>> ac = ahocorasick_rs.AhoCorasick((p.lower() for p in patterns))

AhoCorasick.find_matches_as_indexes() returns a list of tuples, each tuple being:

  1. The index of the found pattern inside the list of patterns.
  2. The start index of the pattern inside the haystack.
  3. The end index of the pattern inside the haystack.
>>> ac.find_matches_as_indexes(haystack)
[(0, 17, 22), (1, 23, 28), (0, 30, 35)]
>>> patterns[0], patterns[1], patterns[0]
('hello', 'world', 'hello')
>>> haystack[17:22], haystack[23:28], haystack[30:35]
('hello', 'world', 'hello')

find_matches_as_strings() returns a list of found patterns:

>>> ac.find_matches_as_strings(haystack)
['hello', 'world', 'hello']

Searching bytes and other similar objects

You can also search bytes, bytearray, memoryview, and other objects supporting the Python buffer API.

>>> patterns = [b"hello", b"world"]
>>> ac = ahocorasick_rs.BytesAhoCorasick(patterns)
>>> haystack = b"hello world"
>>> ac.find_matches_as_indexes(b"hello world")
[(0, 0, 5), (1, 6, 11)]
>>> patterns[0], patterns[1]
(b'hello', b'world')
>>> haystack[0:5], haystack[6:11]
(b'hello', b'world')

The find_matches_as_strings() API is not supported by BytesAhoCorasick.

Choosing the matching algorithm <a name="matching"></a>

Match kind

There are three ways you can configure matching in cases where multiple patterns overlap, supported by both AhoCorasick and BytesAhoCorasick objects. For a more in-depth explanation, see the underlying Rust library's documentation of matching.

Assume we have this starting point:

>>> from ahocorasick_rs import AhoCorasick, MatchKind

Standard (the default)

This returns the pattern that matches first, semantically-speaking. This is the default matching pattern.

>>> ac AhoCorasick(["disco", "disc", "discontent"])
>>> ac.find_matches_as_strings("discontent")
['disc']
>>> ac = AhoCorasick(["b", "abcd"])
>>> ac.find_matches_as_strings("abcdef")
['b']

In this case disc will match before disco or discontent.

Similarly, b will match before abcd because it ends earlier in the haystack than abcd does:

>>> ac = AhoCorasick(["b", "abcd"])
>>> ac.find_matches_as_strings("abcdef")
['b']

LeftmostFirst

This returns the leftmost-in-the-haystack matching pattern that appears first in the list of given patterns. That means the order of patterns makes a difference:

>>> ac = AhoCorasick(["disco", "disc"], matchkind=MatchKind.LeftmostFirst)
>>> ac.find_matches_as_strings("discontent")
['disco']
>>> ac = AhoCorasick(["disc", "disco"], matchkind=MatchKind.LeftmostFirst)
['disc']

Here we see abcd matched first, because it starts before b:

>>> ac = AhoCorasick(["b", "abcd"], matchkind=MatchKind.LeftmostFirst)
>>> ac.find_matches_as_strings("abcdef")
['abcd']
LeftmostLongest

This returns the leftmost-in-the-haystack matching pattern that is longest:

>>> ac = AhoCorasick(["disco", "disc", "discontent"], matchkind=MatchKind.LeftmostLongest)
>>> ac.find_matches_as_strings("discontent")
['discontent']

Overlapping matches

You can get all overlapping matches, instead of just one of them, but only if you stick to the default matchkind, MatchKind.Standard. Again, this is supported by both AhoCorasick and BytesAhoCorasick.

>>> from ahocorasick_rs import AhoCorasick
>>> patterns = ["winter", "onte", "disco", "discontent"]
>>> ac = AhoCorasick(patterns)
>>> ac.find_matches_as_strings("discontent", overlapping=True)
['disco', 'onte', 'discontent']

Additional configuration: speed and memory usage tradeoffs <a name="configuration2"></a>

Algorithm implementations: trading construction speed, memory, and performance (AhoCorasick and BytesAhoCorasick)

You can choose the type of underlying automaton to use, with different performance tradeoffs. The short version: if you want maximum matching speed, and you don't have too many patterns, try the Implementation.DFA implementation and see if it helps.

The underlying Rust library supports four choices, which are exposed as follows:

>>> from ahocorasick_rs import AhoCorasick, Implementation
>>> ac = AhoCorasick(["disco", "disc"], implementation=Implementation.DFA)

Trading memory for speed (AhoCorasick only)

If you use find_matches_as_strings(), there are two ways strings can be constructed: from the haystack, or by caching the patterns on the object. The former takes more work, the latter uses more memory if the patterns would otherwise have been garbage-collected. You can control the behavior by using the store_patterns keyword argument to AhoCorasick().

Implementation details <a name="implementation"></a>

Benchmarks <a name="benchmarks"></a>

As with any benchmark, real-world results will differ based on your particular situation. If performance is important to your application, measure the alternatives yourself!

That being said, I've seen ahocorasick_rs run 1.5× to 7× as fast as pyahocorasick, depending on the options used. You can run the included benchmarks, if you want, to see some comparative results locally. Clone the repository, then:

pip install pytest-benchmark ahocorasick_rs pyahocorasick
pytest benchmarks/