Re2
Ruby bindings to RE2, a "fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python".
Install / Use
/learn @mudge/Re2README
re2 - safer regular expressions in Ruby
Ruby bindings to [RE2][], a "fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python".
Current version: 2.26.1
Bundled RE2 version: libre2.11 (2025-11-05)
RE2('h.*o').full_match?("hello") #=> true
RE2('e').full_match?("hello") #=> false
RE2('h.*o').partial_match?("hello") #=> true
RE2('e').partial_match?("hello") #=> true
RE2('(\w+):(\d+)').full_match("ruby:1234")
#=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
Table of Contents
Why RE2?
While recent versions of Ruby have improved defences against regular expression denial of service (ReDoS) attacks, it is still possible for users to craft malicious patterns that take a long time to process by using syntactic features such as back-references, lookaheads and possessive quantifiers. RE2 aims to eliminate ReDoS by design:
Safety is RE2's raison d'être.
RE2 was designed and implemented with an explicit goal of being able to handle regular expressions from untrusted users without risk. One of its primary guarantees is that the match time is linear in the length of the input string. It was also written with production concerns in mind: the parser, the compiler and the execution engines limit their memory usage by working within a configurable budget – failing gracefully when exhausted – and they avoid stack overflow by eschewing recursion.
— Why RE2?
Usage
Install re2 as a dependency:
# In your Gemfile
gem "re2"
# Or without Bundler
gem install re2
Include in your code:
require "re2"
Full API documentation automatically generated from the latest version is available at https://mudge.name/re2/.
While re2 uses the same naming scheme as Ruby's built-in regular expression
library (with Regexp and
MatchData), its API is slightly
different:
Compiling regular expressions
[!WARNING] RE2's regular expression syntax differs from PCRE and Ruby's built-in
Regexplibrary, see the official syntax page for more details.
The core class is RE2::Regexp which
takes a regular expression as a string and compiles it internally into an RE2
object. A global function RE2 is available to concisely compile a new
RE2::Regexp:
re = RE2('(\w+):(\d+)')
#=> #<RE2::Regexp /(\w+):(\d+)/>
re.ok? #=> true
re = RE2('abc)def')
re.ok? #=> false
re.error #=> "missing ): abc(def"
[!TIP] Note the use of single quotes when passing the regular expression as a string to
RE2so that the backslashes aren't interpreted as escapes.
When compiling a regular expression, an optional second argument can be used to change RE2's default options, e.g. stop logging syntax and execution errors to stderr with log_errors:
RE2('abc)def', log_errors: false)
See the API documentation for RE2::Regexp#initialize for all the available options.
Matching interface
There are two main methods for matching: RE2::Regexp#full_match? requires the regular expression to match the entire input text, and RE2::Regexp#partial_match? looks for a match for a substring of the input text, returning a boolean to indicate whether a match was successful or not.
RE2('h.*o').full_match?("hello") #=> true
RE2('e').full_match?("hello") #=> false
RE2('h.*o').partial_match?("hello") #=> true
RE2('e').partial_match?("hello") #=> true
Submatch extraction
[!TIP] Only extract the number of submatches you need as performance is improved with fewer submatches (with the best performance when avoiding submatch extraction altogether).
Both matching methods have a second form that can extract submatches as RE2::MatchData objects: RE2::Regexp#full_match and RE2::Regexp#partial_match.
m = RE2('(\w+):(\d+)').full_match("ruby:1234")
#=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
m[0] #=> "ruby:1234"
m[1] #=> "ruby"
m[2] #=> "1234"
m = RE2('(\w+):(\d+)').full_match("r")
#=> nil
RE2::MatchData supports retrieving submatches by numeric index or by name if present in the regular expression:
m = RE2('(?P<word>\w+):(?P<number>\d+)').full_match("ruby:1234")
#=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
m["word"] #=> "ruby"
m["number"] #=> "1234"
Multiple submatches can be retrieved at the same time by numeric index or name with values_at:
m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
#=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
m.values_at("word", :number, 3)
#=> ["ruby", "1234", "5678"]
All captures can be returned as an array with captures:
m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
#=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
m.captures #=> ["ruby", "1234", "5678"]
Capturing group names are available on both RE2::Regexp and RE2::MatchData:
re = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)')
re.names #=> ["number", "word"]
m = re.full_match("ruby:1234:5678")
m.names #=> ["number", "word"]
Named captures can be returned as a hash with named_captures:
m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
#=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
m.named_captures
#=> {"number" => "1234", "word" => "ruby"}
m.named_captures(symbolize_names: true)
#=> {number: "1234", word: "ruby"}
This is also available on the original RE2::Regexp but will return the corresponding numerical index for each group:
re = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)')
re.named_captures
#=> {"number" => 2, "word" => 1}
The strings before and after a match can be returned with pre_match and post_match:
m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
m.pre_match #=> "bob "
m.post_match #=> " 456"
The offset and match_length of a match can be retrieved by index or name:
m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
m.offset(1) #=> [4, 7]
m.match_length(1) #=> 3
RE2::MatchData objects can also be used with Ruby's pattern matching:
case RE2('(\w+):(\d+)').full_match("ruby:1234")
in [word, number]
puts "Word: #{word}, Number: #{number}"
else
puts "No match"
end
# Word: ruby, Number: 1234
case RE2('(?P<word>\w+):(?P<number>\d+)').full_match("ruby:1234")
in word:, number:
puts "Word: #{word}, Number: #{number}"
else
puts "No match"
end
# Word: ruby, Number: 1234
By default, both full_match and partial_match will extract all submatches into the RE2::MatchData based on the number of capturing groups in the regular expression. This can be changed by passing an optional second argument when matching:
m = RE2('(\w+):(\d+)').full_match("ruby:1234", submatches: 1)
=> #<RE2::MatchData "ruby:1234" 1:"ruby">
[!WARNING] If the regular expression has no capturing groups or you pass
submatches: 0, the matching method will behave like itsfull_match?orpartial_match?form and only returntrueorfalserather thanRE2::MatchData.
Scanning text incrementally
If you want to repeatedly match regular expressions from the start of some input text, you can use RE2::Regexp#scan to return an Enumerable RE2::Scanner object which will lazily consume matches as you iterate over it:
`
