Quickly match many regexes against a string. Provides 2-10x speedups over naïve regex matching.
Maintained. Last release 6 months ago, commits in 3 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install multiregexmultiregex
Quickly match many regexes against a string. Provides 2-10x speedups over naïve regex matching.
Introduction
See this introductory blog post.
Installation
This project is managed by pixi. You can install the package in development mode using:
git clone https://github.com/quantco/multiregex
cd multiregex
pixi run pre-commit-install
pixi run postinstall
pixi run test
Usage
import multiregex
# Create matcher from multiple regexes.
my_patterns = [r"\w+@\w+\.com", r"\w\.com"]
matcher = multiregex.RegexMatcher(my_patterns)
# Run `re.search` for all regexes.
# Returns a set of matches as (re.Pattern, re.Match) tuples.
matcher.search("john.doe@example.com")
# => [(re.compile('\\w+@\\w+\\.com'), <re.Match ... 'doe@example.com'>),
# (re.compile('\\w+\\.com'), <re.Match ... 'example.com'>)]
# Same as above, but with `re.match`.
matcher.match(...)
# Same as above, but with `re.fullmatch`.
matcher.fullmatch(...)
Custom prematchers
To be able to quickly match many regexes against a string, multiregex uses
"prematchers" under the hood. Prematchers are lists of non-regex strings of which
at least one can be assumed to be present in the haystack if the corresponding regex matches.
As an example, a valid prematcher of r"\w+\.com" could be [".com"] and a valid
prematcher of r"(B|b)aNäNa" could be ["b"] or ["anäna"].
Note that prematchers must be all-lowercase (in order for multiregex to be able to support ).