# Python regular-expression libraries

Python regex libraries match text against regular expression patterns with features beyond the standard library's re module. Some libraries bind a separate engine such as Hyperscan or Oniguruma rather than extending the re module. These libraries let search tools, log scanners, and AI agents match patterns against large volumes of text.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [regex](#regex) | 391.9M | 609 | Nov 2026 | Apache-2.0 AND CNRI-Python |
| [google-re2](#google-retwo) | 25.0M | Not on GitHub | Nov 2025 | BSD-3-Clause |
| [hyperscan](#hyperscan) | 830.6K | Not on GitHub | Oct 2026 | MIT |
| [pyre2](#pyre) | 315.2K | 109 | Sep 2026 | BSD-3-Clause |
| [onigurumacffi](#onigurumacffi) | 280.7K | Not on GitHub | Jan 2026 | MIT |
| [pyperscan](#pyperscan) | 50.6K | 17 | Oct 2026 | MIT OR Apache-2.0 |
| [pcre2](#pcretwo) | 39.4K | Not on GitHub | Jul 2026 | BSD-3-Clause |
| [re2](#retwo) | 4.6K | Not on GitHub | Feb 2019 | BSD-3-Clause |

Downloads: pypi, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[regex](#regex) has the most monthly downloads in this comparison, at 391.9M.

## Capabilities

| Library | Streaming scan state | Replacement API | Multi-pattern database |
| --- | --- | --- | --- |
| [regex](#regex) | No | Yes | No |
| [google-re2](#google-retwo) | No | Yes | Yes |
| [hyperscan](#hyperscan) | Yes | No | Yes |
| [pyre2](#pyre) | No | Yes | No |
| [onigurumacffi](#onigurumacffi) | No | No | Yes |
| [pyperscan](#pyperscan) | Yes | No | Yes |
| [pcre2](#pcretwo) | No | Yes | No |
| [re2](#retwo) | No | Yes | No |

## Libraries

### regex

[GitHub](https://github.com/mrabarnett/mrab-regex) · [pypi](https://pypi.org/project/regex) · [Docs](https://pypi.org/pypi/regex/2026.11.15/json)

Extends Python’s regular-expression interface with additional matching features.

- Downloads / mo: 391.9M
- Stars: 609
- Last release: 2026.11.15
- License: Apache-2.0 AND CNRI-Python
- Capabilities: [From the regex docs](https://pypi.org/pypi/regex/2026.11.15/json)

**Strengths**

- **Retains repeated capture history.** Use captures to retrieve every capture of a repeated named group.
- **Supports full Unicode case-folding.** Enable FULLCASE with IGNORECASE for full Unicode case-insensitive matching.

**Watch out for**

- **Fuzzy matching needs quality settings.** Enable BESTMATCH when the best fuzzy result is required.
- **Concurrent matching needs unchanged input.** Keep input unchanged when concurrent matching releases the GIL.

```sh
python -m pip install regex==2026.11.15
```

**nltk/nltk** (14.8K stars)

[nltk/nltk](https://github.com/nltk/nltk) 

```python
def compile(pattern, flags=0, timeout=_UNSET):
    r"""Compile ``pattern`` with the :mod:`regex` engine and wrap it so every
    match runs under a wall-clock timeout.

    :param pattern: a regular-expression string, or an already-compiled
        ``re``/``regex`` pattern (its ``.pattern`` is re-compiled with
        ``regex``), or an existing :class:`TimedPattern` (returned as-is with
        the requested timeout).
    :param flags: regex flags (stdlib ``re`` flag constants are accepted).
    :param timeout: default wall-clock limit for matches on the returned
        pattern; ``None`` disables it. Omit to use :data:`DEFAULT_TIMEOUT` at
        match time (so a later change to that module attribute still applies).
    :rtype: TimedPattern
    """
    if isinstance(pattern, TimedPattern):
        if timeout is _UNSET:
            return pattern
        return TimedPattern(pattern._rx, timeout)
    # Accept a pre-compiled ``re``/``regex`` pattern by re-compiling its source.
    src = getattr(pattern, "pattern", pattern)
    check_pattern(src)
    try:
        compiled = regex.compile(src, flags)
    except regex.error as exc:
        # Normalise the engine's error to a re.error subclass so callers that
        # catch re.error still work after moving off the stdlib module.
        raise error(str(exc)) from exc
    return TimedPattern(compiled, timeout)
```

[nltk/redos.py](https://github.com/nltk/nltk/blob/0ed5528a28c40e8071fe54cf370fc3020a287496/nltk/redos.py#L283-L310) · [More projects using regex →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20regex%20for%20regular%20expressions%20extraction%20pattern%20compilation%20timeouts%20and%20streaming%20signature%20scanning&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import regex

print(regex.search(r"\w+", "hello").group())

```

From [README.rst](https://pypi.org/pypi/regex/2026.11.15/json)

### google-re2

[GitHub](https://github.com/google/re2) · [pypi](https://pypi.org/project/google-re2) · [Docs](https://github.com/google/re2/blob/2025-11-05/python/re2.py)

Binds Google's RE2 engine to Python.

- Downloads / mo: 25.0M
- Last release: 1.1.20251105
- License: BSD-3-Clause
- Capabilities: [From the google-re2 docs](https://github.com/google/re2/blob/2025-11-05/python/re2.py)

```sh
python -m pip install google-re2==1.1.20251105
```

**zulip/zulip** (26.3K stars)

[zulip/zulip](https://github.com/zulip/zulip) 

```python
def filter_pattern_validator(value: str) -> "re2._Regexp[str]":
    try:
        # Do not write errors to stderr (this still raises exceptions)
        options = re2.Options()
        options.log_errors = False

        regex = re2.compile(value, options=options)
    except re2.error as e:
        if len(e.args) >= 1:
            if isinstance(e.args[0], str):  # nocoverage
                raise ValidationError(_("Bad regular expression: {regex}").format(regex=e.args[0]))
            if isinstance(e.args[0], bytes):
                raise ValidationError(
                    _("Bad regular expression: {regex}").format(regex=e.args[0].decode())
                )
        raise ValidationError(_("Unknown regular expression error"))  # nocoverage

    return regex
```

[zerver/models/linkifiers.py](https://github.com/zulip/zulip/blob/d770d79da7924cc7720fa8463d13d729ad6f3753/zerver/models/linkifiers.py#L64-L81) · [More projects using google-re2 →](https://dashboard.exa.ai/playground/search?q=google-re2%20GitHub%20projects)

**Quickstart**

```python
import re2

print(re2.search(r"\w+", "hello").group())

```

From [README.md](https://github.com/google/re2/blob/2025-11-05/python/re2.py)

### hyperscan

[GitHub](https://github.com/darvid/python-hyperscan) · [pypi](https://pypi.org/project/hyperscan) · [Docs](https://python-hyperscan.readthedocs.io/en/latest/usage/)

Binds the Hyperscan engine to Python.

- Downloads / mo: 830.6K
- Last release: 0.9.1
- License: MIT
- Capabilities: [From the hyperscan docs](https://python-hyperscan.readthedocs.io/en/latest/usage/)

```sh
python -m pip install hyperscan==0.9.1
```

**funstory-ai/BabelDOC** (9.9K stars)

[funstory-ai/BabelDOC](https://github.com/funstory-ai/BabelDOC) 

```python
def _build_regex_and_lookup(self):
    logger.debug(
        f"start build regex for glossary {self.name} with {len(self.entries)} entries"
    )
    """
    Builds a combined regex for all source terms and a lookup dictionary
    from normalized source terms to (original_source, original_target).
    Regex patterns are sorted by length in descending order to prioritize longer matches.
    """
    self.normalized_lookup = {}

    if not self.entries:
        self.source_terms_regex = None
        return

    self.hs_dbs = []
    hs_pattern = []
    start = time.time()
    for idx, entry in enumerate(self.entries):
        normalized_key = self.normalize_source(entry.source)
        self.normalized_lookup[normalized_key] = (entry.source, entry.target)
        self.id_lookup.append((entry.source, entry.target))

        hs_pattern.append((re.escape(entry.source).encode("utf-8"), idx))

    chunk_size = 20000
    for i, pattern_chunk in enumerate(
        batched(hs_pattern, chunk_size, strict=False)
    ):
        logger.debug(
            f"building hs_db chunk {i + 1} / {len(self.entries) // chunk_size + 1}"
        )
        expressions, ids = zip(*pattern_chunk, strict=False)

        hs_db = hyperscan.Database()
        hs_db.compile(
            expressions=expressions,
            ids=ids,
            elements=len(pattern_chunk),
            flags=hyperscan.HS_FLAG_CASELESS | hyperscan.HS_FLAG_SINGLEMATCH,
            # | hyperscan.HS_FLAG_UTF8
            # | hyperscan.HS_FLAG_UCP,
        )
        self.hs_dbs.append(hs_db)

    end = time.time()
    logger.debug(
        f"finished building regex for glossary {self.name} in {end - start:.2f} seconds"
    )
    logger.debug(
        f"build hs database for glossary {self.name} with {len(self.entries)} entries, hs_info: {self.hs_dbs[0].info()}"
    )
    if not self.hs_dbs:
        self.hs_dbs = None
```

[babeldoc/glossary.py](https://github.com/funstory-ai/BabelDOC/blob/dd9adc352b957533d05b8cb94e88a7589cc56a35/babeldoc/glossary.py#L97-L150) · [More projects using hyperscan →](https://dashboard.exa.ai/playground/search?q=hyperscan%20GitHub%20projects)

**Quickstart**

```python
import hyperscan

db = hyperscan.Database()
db.compile(expressions=[b"foo"], ids=[0])
db.scan(b"foobar", match_event_handler=lambda *event: print(event))

```

From [README.md](https://python-hyperscan.readthedocs.io/en/latest/usage/)

### pyre2

[GitHub](https://github.com/andreasvc/pyre2) · [pypi](https://pypi.org/project/pyre2) · [Docs](https://api.github.com/repos/andreasvc/pyre2/git/blobs/db88a57fd4e0beb82483f6c0af2ba68803612de4)

Wraps Google’s RE2 engine behind a Python regular-expression interface.

- Downloads / mo: 315.2K
- Stars: 109
- Last release: 0.3.14
- License: BSD-3-Clause
- Capabilities: [From the pyre2 docs](https://api.github.com/repos/andreasvc/pyre2/git/blobs/db88a57fd4e0beb82483f6c0af2ba68803612de4)

**Strengths**

- **Can reject engine fallback.** Set FALLBACK_EXCEPTION when unsupported patterns must raise instead of switching engines.
- **Matches Unicode property classes.** Use named Unicode classes such as Greek in patterns.

**Watch out for**

- **Unsupported patterns switch engines.** Patterns outside RE2’s syntax fall back to Python re.
- **Byte input produces byte offsets.** Match offsets refer to bytes when matching UTF-8 byte strings.

```sh
python -m pip install pyre2==0.3.14
```

**simple-login/app** (7.2K stars)

[simple-login/app](https://github.com/simple-login/app) 

```python
def regex_match(rule_regex: str, local):
    regex = re2.compile(rule_regex)
    try:
        if re2.fullmatch(regex, local):
            return True
    except TypeError:  # re2 bug "Argument 'pattern' has incorrect type (expected bytes, got PythonRePattern)"
        LOG.w("use re instead of re2 for %s %s", rule_regex, local)
        regex = re.compile(rule_regex)
        if re.fullmatch(regex, local):
            return True
    return False
```

[app/regex_utils.py](https://github.com/simple-login/app/blob/4d5d8c18f7cdbc257e01c9f4cc2c929c5acbf839/app/regex_utils.py#L8-L18) · [More projects using pyre2 →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pyre2%20for%20regular%20expressions%20extraction%20pattern%20compilation%20timeouts%20and%20streaming%20signature%20scanning&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import re2

print(re2.search(r"\w+", "hello").group())

```

From [README.rst](https://api.github.com/repos/andreasvc/pyre2/git/blobs/db88a57fd4e0beb82483f6c0af2ba68803612de4)

### onigurumacffi

[GitHub](https://github.com/asottile/onigurumacffi) · [pypi](https://pypi.org/project/onigurumacffi) · [Docs](https://api.github.com/repos/asottile/onigurumacffi/readme)

Binds the Oniguruma regex engine to Python through cffi.

- Downloads / mo: 280.7K
- Last release: 1.5.0
- License: MIT
- Capabilities: [From the onigurumacffi docs](https://api.github.com/repos/asottile/onigurumacffi/readme)

```sh
python -m pip install onigurumacffi==1.5.0
```

**asottile/babi** (490 stars)

[asottile/babi](https://github.com/asottile/babi) 

```python
def search(
        self,
        line: str,
        pos: int,
        first_line: bool,
        boundary: bool,
) -> Match[str] | None:
    return self._reg.search(line, pos, flags=_FLAGS[first_line, boundary])
```

[babi/reg.py](https://github.com/asottile/babi/blob/2cb63abc6b1ebcfddab3bcedd9aef9893d5f624d/babi/reg.py#L39-L46) · [More projects using onigurumacffi →](https://dashboard.exa.ai/playground/search?q=onigurumacffi%20GitHub%20projects)

**Quickstart**

```python
import onigurumacffi

pattern = onigurumacffi.compile(r"\w+")
print(pattern.search("hello").group())

```

From [README.md](https://api.github.com/repos/asottile/onigurumacffi/readme)

### pyperscan

[GitHub](https://github.com/vlaci/pyperscan) · [pypi](https://pypi.org/project/pyperscan) · [Docs](https://vlaci.github.io/pyperscan/usage/)

Provides Python bindings to the Hyperscan pattern-scanning engine.

- Downloads / mo: 50.6K
- Stars: 17
- Last release: 0.4.0
- License: MIT OR Apache-2.0
- Capabilities: [From the pyperscan docs](https://vlaci.github.io/pyperscan/usage/)

**Strengths**

- **Combines multiple tagged patterns.** Build a pattern database and identify matches through their tags.
- **Supports incremental stream scanning.** Use StreamDatabase when matching data across stream chunks.

**Watch out for**

- **Start offsets need a flag.** Set SOM_LEFTMOST when callbacks need the match’s start offset.

```sh
python -m pip install pyperscan==0.4.0
```

**onekey-sec/unblob** (2.7K stars)

[onekey-sec/unblob](https://github.com/onekey-sec/unblob) 

```python
@lru_cache
def build_hyperscan_database(handlers: Handlers) -> StreamDatabase:
    patterns = []
    for handler_class in handlers:
        handler = handler_class()
        for pattern in handler.PATTERNS:
            try:
                patterns.append(
                    Pattern(
                        pattern.as_regex(),
                        Flag.SOM_LEFTMOST,
                        Flag.DOTALL,
                        tag=handler,
                    )
                )
            except InvalidHexString as e:
                logger.error(
                    "Invalid pattern",
                    handler=handler.NAME,
                    pattern=pattern,
                    error=str(e),
                )
                raise
    return StreamDatabase(*patterns)
```

[python/unblob/finder.py](https://github.com/onekey-sec/unblob/blob/d057b3a0435c61b91cc03bed1933499c14f06735/python/unblob/finder.py#L173-L196) · [More projects using pyperscan →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pyperscan%20for%20regular%20expressions%20extraction%20pattern%20compilation%20timeouts%20and%20streaming%20signature%20scanning&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import pyperscan as ps

def on_match(context, tag, start, end):
    context.append((tag, start, end))
    return ps.Scan.Continue

matches = []
db = ps.BlockDatabase(ps.Pattern(b"foo", ps.Flag.SOM_LEFTMOST))
scanner = db.build(matches, on_match)
scanner.scan(b"foobar")
print(matches)

```

From [usage.md](https://vlaci.github.io/pyperscan/usage/)

### pcre2

[GitHub](https://github.com/grtetrault/pcre2.py) · [pypi](https://pypi.org/project/pcre2) · [Docs](https://api.github.com/repos/grtetrault/pcre2.py/readme)

Binds the PCRE2 regular expression library to Python.

- Downloads / mo: 39.4K
- Last release: 0.7.1
- License: BSD-3-Clause
- Capabilities: [From the pcre2 docs](https://api.github.com/repos/grtetrault/pcre2.py/readme)

```sh
python -m pip install pcre2==0.7.1
```

**Quickstart**

```python
import pcre2

pattern = pcre2.compile(r"\w+")
print(pattern.search("hello").group())

```

From [README.md](https://api.github.com/repos/grtetrault/pcre2.py/readme) · [Find projects using pcre2 →](https://dashboard.exa.ai/playground/search?q=pcre2%20GitHub%20projects)

### re2

[GitHub](https://github.com/axiak/pyre2) · [pypi](https://pypi.org/project/re2) · [Docs](https://api.github.com/repos/axiak/pyre2/readme)

Wraps Google's RE2 engine through Cython.

- Downloads / mo: 4.6K
- Last release: 0.2.24
- License: BSD-3-Clause
- Capabilities: [From the re2 docs](https://api.github.com/repos/axiak/pyre2/readme)

```sh
python -m pip install re2==0.2.24
```

**Quickstart**

```python
import re2

print(re2.search(r"\w+", "hello").group())

```

From [README.rst](https://api.github.com/repos/axiak/pyre2/readme) · [Find projects using re2 →](https://dashboard.exa.ai/playground/search?q=re2%20GitHub%20projects)

## FAQ

### Which Python regex library should I use?

The standard library's re module covers most patterns. [regex](#regex) suits code that needs repeated capture history, full Unicode case-folding, or fuzzy matching. [google-re2](#google-retwo) suits code that needs Google's regex engine. [hyperscan](#hyperscan) suits scanning text against many patterns at once.

### Which regular expression engine is bundled with Python?

The re module supplies regular expression operations in Python's standard library. It ships with Python and needs no install.

### Does a repeated re group return every captured value?

No. The re module keeps only the last capture of a group that matches repeatedly. The [regex](#regex) module's captures method returns the full capture history for a named group.

### Can re mix a bytes pattern with a Unicode string?

No. The pattern, the input, and any replacement must share one type, either Unicode strings or bytes.

### Does regex fuzzy matching choose the best match?

Not by default. The BESTMATCH flag changes fuzzy matching from the next match to the best match.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python regex libraries re regex pyre2 pyperscan code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
