Usage

Full API reference · More examples

Matches

type match_ = { pattern : int; start : int; stop : int }

pattern is the zero-based pattern index. The span [start, stop) uses byte offsets. Get the original pattern with Aho_corasick.pattern matcher m.pattern.

Build once

let matcher = Aho_corasick.build ~ignore_case:true [ "cat"; "dog" ]

Automata are immutable and reusable across threads. ignore_case defaults to false and folds ASCII only.

Search and replace

FunctionResult
find_allAll overlapping matches, as a list
find_iterThe same matches, as a lazy Seq.t
find_leftmost_longestNon-overlapping leftmost-longest matches
memWhether any pattern matches
replace_allReplace leftmost-longest matches using a callback
let output =
  Aho_corasick.replace_all matcher "Cat and DOG" ~f:(fun _ -> "[pet]")
(* "[pet] and [pet]" *)

Stream across chunks

let matcher = Aho_corasick.build [ "he"; "she"; "his"; "hers" ]
let state = Aho_corasick.Stream.start matcher
let state, first = Aho_corasick.Stream.feed matcher state "ush"
let state, second = Aho_corasick.Stream.feed matcher state "ers"
(* first = []; second: she 1..4, he 2..4, hers 2..6 *)

Use the same matcher and the returned state on each call. Empty chunks are allowed. Offsets are absolute from the start of the stream.

ModeAPIFinish
All overlapsStream.feedNo flush
Earliest end, non-overlappingStream.feed_nonoverlappingNo flush
Leftmost-longestStream.Leftmost_longestflush
Replace leftmost-longestStream.ReplaceAppend flush output

Use one mode throughout a stream. Leftmost-longest modes use lookahead bounded by the longest pattern; finish with flush and do not feed the finished state again.

Streamed replacement

module R = Aho_corasick.Stream.Replace
let matcher = Aho_corasick.build [ "Sam"; "Samwise" ]
let state = R.start matcher ~f:(fun _ -> "[name]")
let state, first = R.feed matcher state "Sam"
let state, second = R.feed matcher state "wise and Sam"
let output = first ^ second ^ R.flush state
(* "[name] and [name]" *)

For long streams, write each piece to an output channel or buffer.

Performance

All searches scan once. Overlapping modes additionally allocate every reported match; leftmost-longest modes keep one candidate per start in a longest-pattern window. See the cost details and benchmarks.