re2 provides Ruby bindings to Google's RE2 regular expression library, which guarantees linear time execution regardless of input or pattern complexity. Unlike Ruby's default Onigmo engine, RE2 trades some features for predictable performance and protection against catastrophic backtracking. The gem offers a safer alternative for processing untrusted input or patterns where execution time guarantees are critical.
The library implements a subset of the PCRE syntax, supporting most common regular expression features while excluding constructs that could cause exponential matching time. It provides a drop-in replacement interface similar to Ruby's Regexp class, with methods for matching, scanning, and substitution. RE2 uses a DFA-based matching algorithm that ensures O(n) time complexity regardless of pattern complexity, making it immune to ReDoS (Regular Expression Denial of Service) attacks that can affect traditional backtracking engines.
re2 is essential for applications processing user-supplied regular expressions or matching patterns against untrusted input, particularly in web applications, log processors, and text analysis systems. It's commonly used in scenarios where regex execution time must be bounded, such as API input validation, rate-limited services, and systems processing high volumes of pattern matching. While it doesn't support all Perl-compatible features like backreferences, its performance guarantees make it the right choice when reliability and security matter more than feature completeness.
gem install re2 Run this gem instantly in your browser without any installation:
Open in RunRuby.dev →All 59 versions available for installation