Google RE2 Python Bindings

1.1.20251105 · active · verified Thu Apr 09

google-re2 provides Python bindings for Google's high-performance RE2 C++ regular expression library. It offers a fast and secure alternative to Python's built-in `re` module, designed for linear-time execution, but with a more restricted feature set. The library maintains a frequent release cadence, often monthly, reflecting updates to the underlying C++ library.

Warnings

Install

Imports

Quickstart

This example demonstrates basic usage of the `re2` module, including compiling patterns, searching, finding all matches, and performing substitutions. The API largely mirrors Python's built-in `re` module for common operations.

import re2

# Compile a regex pattern
pattern = re2.compile(r'hello (\w+)')

# Search for a match
match = pattern.search('hello world')
if match:
    print(f"Found: {match.group(0)}")
    print(f"Captured: {match.group(1)}")

# Find all occurrences
text = 'hello python, hello universe'
all_matches = re2.findall(r'hello (\w+)', text)
print(f"All matches: {all_matches}")

# Replace text
replaced_text = re2.sub(r'hello', 'hi', text)
print(f"Replaced text: {replaced_text}")

view raw JSON →