Debian Codegraph @

README.md

raw symbols SCIP
1 # re2 - safer regular expressions in Ruby
2
3 Ruby bindings to [RE2][], a "fast, safe, thread-friendly alternative to
4 backtracking regular expression engines like those used in PCRE, Perl, and
5 Python".
6
7 [![Build Status](https://github.com/mudge/re2/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/mudge/re2/actions)
8
9 **Current version:** 2.27.0
10 **Bundled RE2 version:** libre2.11 (2025-11-05)
11
12 ```ruby
13 RE2('h.*o').full_match?("hello") #=> true
14 RE2('e').full_match?("hello") #=> false
15 RE2('h.*o').partial_match?("hello") #=> true
16 RE2('e').partial_match?("hello") #=> true
17 RE2('(\w+):(\d+)').full_match("ruby:1234")
18 #=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
19 ```
20
21 ## Table of Contents
22
23 * [Why RE2?](#why-re2)
24 * [Usage](#usage)
25 * [Compiling regular expressions](#compiling-regular-expressions)
26 * [Matching interface](#matching-interface)
27 * [Submatch extraction](#submatch-extraction)
28 * [Scanning text incrementally](#scanning-text-incrementally)
29 * [Searching simultaneously](#searching-simultaneously)
30 * [Replacing and extracting](#replacing-and-extracting)
31 * [Escaping](#escaping)
32 * [Encoding](#encoding)
33 * [Requirements](#requirements)
34 * [Native gems](#native-gems)
35 * [Verifying the gems](#verifying-the-gems)
36 * [Installing the `ruby` platform gem](#installing-the-ruby-platform-gem)
37 * [Using system libraries](#using-system-libraries)
38 * [Thanks](#thanks)
39 * [Contact](#contact)
40 * [License](#license)
41 * [Dependencies](#dependencies)
42
43 ## Why RE2?
44
45 While [recent
46 versions](https://www.ruby-lang.org/en/news/2022/12/25/ruby-3-2-0-released/) of
47 Ruby have improved defences against [regular expression denial of service
48 (ReDoS) attacks](https://en.wikipedia.org/wiki/ReDoS), it is still possible for
49 users to craft malicious patterns that take a long time to process by using
50 syntactic features such as [back-references, lookaheads and possessive
51 quantifiers](https://bugs.ruby-lang.org/issues/19104#note-3). RE2 aims to
52 eliminate ReDoS by design:
53
54 > **_Safety is RE2's raison d'être._**
55 >
56 > RE2 was designed and implemented with an explicit goal of being able to
57 > handle regular expressions from untrusted users without risk. One of its
58 > primary guarantees is that the match time is linear in the length of the
59 > input string. It was also written with production concerns in mind: the
60 > parser, the compiler and the execution engines limit their memory usage by
61 > working within a configurable budget – failing gracefully when exhausted –
62 > and they avoid stack overflow by eschewing recursion.
63
64 — [Why RE2?](https://github.com/google/re2/wiki/WhyRE2)
65
66 ## Usage
67
68 Install re2 as a dependency:
69
70 ```ruby
71 # In your Gemfile
72 gem "re2"
73
74 # Or without Bundler
75 gem install re2
76 ```
77
78 Include in your code:
79
80 ```ruby
81 require "re2"
82 ```
83
84 Full API documentation automatically generated from the latest version is
85 available at https://mudge.name/re2/.
86
87 While re2 uses the same naming scheme as Ruby's built-in regular expression
88 library (with [`Regexp`](https://mudge.name/re2/RE2/Regexp.html) and
89 [`MatchData`](https://mudge.name/re2/RE2/MatchData.html)), its API is slightly
90 different:
91
92 ### Compiling regular expressions
93
94 > [!WARNING]
95 > RE2's regular expression syntax differs from PCRE and Ruby's built-in
96 > [`Regexp`](https://docs.ruby-lang.org/en/3.2/Regexp.html) library, see the
97 > [official syntax page](https://github.com/google/re2/wiki/Syntax) for more
98 > details.
99
100 The core class is [`RE2::Regexp`](https://mudge.name/re2/RE2/Regexp.html) which
101 takes a regular expression as a string and compiles it internally into an `RE2`
102 object. A global function `RE2` is available to concisely compile a new
103 `RE2::Regexp`:
104
105 ```ruby
106 re = RE2('(\w+):(\d+)')
107 #=> #<RE2::Regexp /(\w+):(\d+)/>
108 re.ok? #=> true
109
110 re = RE2('abc)def')
111 re.ok? #=> false
112 re.error #=> "missing ): abc(def"
113 ```
114
115 > [!TIP]
116 > Note the use of *single quotes* when passing the regular expression as
117 > a string to `RE2` so that the backslashes aren't interpreted as escapes.
118
119 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`:
120
121 ```ruby
122 RE2('abc)def', log_errors: false)
123 ```
124
125 See the API documentation for [`RE2::Regexp#initialize`](https://mudge.name/re2/RE2/Regexp.html#initialize-instance_method) for all the available options.
126
127 ### Matching interface
128
129 There are two main methods for matching: [`RE2::Regexp#full_match?`](https://mudge.name/re2/RE2/Regexp.html#full_match%3F-instance_method) requires the regular expression to match the entire input text, and [`RE2::Regexp#partial_match?`](https://mudge.name/re2/RE2/Regexp.html#partial_match%3F-instance_method) looks for a match for a substring of the input text, returning a boolean to indicate whether a match was successful or not.
130
131 ```ruby
132 RE2('h.*o').full_match?("hello") #=> true
133 RE2('e').full_match?("hello") #=> false
134
135 RE2('h.*o').partial_match?("hello") #=> true
136 RE2('e').partial_match?("hello") #=> true
137 ```
138
139 ### Submatch extraction
140
141 > [!TIP]
142 > Only extract the number of submatches you need as performance is improved
143 > with fewer submatches (with the best performance when avoiding submatch
144 > extraction altogether).
145
146 Both matching methods have a second form that can extract submatches as [`RE2::MatchData`](https://mudge.name/re2/RE2/MatchData.html) objects: [`RE2::Regexp#full_match`](https://mudge.name/re2/RE2/Regexp.html#full_match-instance_method) and [`RE2::Regexp#partial_match`](https://mudge.name/re2/RE2/Regexp.html#partial_match-instance_method).
147
148 ```ruby
149 m = RE2('(\w+):(\d+)').full_match("ruby:1234")
150 #=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
151
152 m[0] #=> "ruby:1234"
153 m[1] #=> "ruby"
154 m[2] #=> "1234"
155
156 m = RE2('(\w+):(\d+)').full_match("r")
157 #=> nil
158 ```
159
160 `RE2::MatchData` supports retrieving submatches by numeric index or by name if present in the regular expression:
161
162 ```ruby
163 m = RE2('(?P<word>\w+):(?P<number>\d+)').full_match("ruby:1234")
164 #=> #<RE2::MatchData "ruby:1234" 1:"ruby" 2:"1234">
165
166 m["word"] #=> "ruby"
167 m["number"] #=> "1234"
168 ```
169
170 Multiple submatches can be retrieved at the same time by numeric index or name with [`values_at`](https://mudge.name/re2/RE2/MatchData.html#values_at-instance_method):
171
172 ```ruby
173 m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
174 #=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
175
176 m.values_at("word", :number, 3)
177 #=> ["ruby", "1234", "5678"]
178 ```
179
180 All captures can be returned as an array with [`captures`](https://mudge.name/re2/RE2/MatchData.html#captures-instance_method):
181
182 ```ruby
183 m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
184 #=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
185
186 m.captures #=> ["ruby", "1234", "5678"]
187 ```
188
189 Capturing group names are available on both `RE2::Regexp` and `RE2::MatchData`:
190
191 ```ruby
192 re = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)')
193 re.names #=> ["number", "word"]
194
195 m = re.full_match("ruby:1234:5678")
196 m.names #=> ["number", "word"]
197 ```
198
199 Named captures can be returned as a hash with [`named_captures`](https://mudge.name/re2/RE2/MatchData.html#named_captures-instance_method):
200
201 ```ruby
202 m = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)').full_match("ruby:1234:5678")
203 #=> #<RE2::MatchData "ruby:1234:5678" 1:"ruby" 2:"1234" 3:"5678">
204
205 m.named_captures
206 #=> {"number" => "1234", "word" => "ruby"}
207 m.named_captures(symbolize_names: true)
208 #=> {number: "1234", word: "ruby"}
209 ```
210
211 This is [also available](https://mudge.name/re2/RE2/Regexp.html#named_captures-instance_method) on the original `RE2::Regexp` but will return the corresponding numerical index for each group:
212
213 ```ruby
214 re = RE2('(?P<word>\w+):(?P<number>\d+):(\d+)')
215 re.named_captures
216 #=> {"number" => 2, "word" => 1}
217 ```
218
219 The strings before and after a match can be returned with [`pre_match`](https://mudge.name/re2/RE2/MatchData.html#pre_match-instance_method) and [`post_match`](https://mudge.name/re2/RE2/MatchData.html#post_match-instance_method):
220
221 ```ruby
222 m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
223 m.pre_match #=> "bob "
224 m.post_match #=> " 456"
225 ```
226
227 The [`offset`](https://mudge.name/re2/RE2/MatchData.html#offset-instance_method) and [`match_length`](https://mudge.name/re2/RE2/MatchData.html#match_length-instance_method) of a match can be retrieved by index or name:
228
229 ```ruby
230 m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
231 m.offset(1) #=> [4, 7]
232 m.match_length(1) #=> 3
233 ```
234
235 `RE2::MatchData` objects can also be used with Ruby's [pattern matching](https://docs.ruby-lang.org/en/3.2/syntax/pattern_matching_rdoc.html):
236
237 ```ruby
238 case RE2('(\w+):(\d+)').full_match("ruby:1234")
239 in [word, number]
240 puts "Word: #{word}, Number: #{number}"
241 else
242 puts "No match"
243 end
244 # Word: ruby, Number: 1234
245
246 case RE2('(?P<word>\w+):(?P<number>\d+)').full_match("ruby:1234")
247 in word:, number:
248 puts "Word: #{word}, Number: #{number}"
249 else
250 puts "No match"
251 end
252 # Word: ruby, Number: 1234
253 ```
254
255 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:
256
257 ```ruby
258 m = RE2('(\w+):(\d+)').full_match("ruby:1234", submatches: 1)
259 => #<RE2::MatchData "ruby:1234" 1:"ruby">
260 ```
261
262 > [!WARNING]
263 > If the regular expression has no capturing groups or you pass `submatches:
264 > 0`, the matching method will behave like its `full_match?` or
265 > `partial_match?` form and only return `true` or `false` rather than
266 > `RE2::MatchData`.
267
268 ### Scanning text incrementally
269
270 If you want to repeatedly match regular expressions from the start of some input text, you can use [`RE2::Regexp#scan`](https://mudge.name/re2/RE2/Regexp.html#scan-instance_method) to return an `Enumerable` [`RE2::Scanner`](https://mudge.name/re2/RE2/Scanner.html) object which will lazily consume matches as you iterate over it:
271
272 ```ruby
273 scanner = RE2('(\w+)').scan(" one two three 4")
274 scanner.each do |match|
275 puts match.inspect
276 end
277 # ["one"]
278 # ["two"]
279 # ["three"]
280 # ["4"]
281 ```
282
283 ### Searching simultaneously
284
285 [`RE2::Set`](https://mudge.name/re2/RE2/Set.html) represents a collection of
286 regular expressions that can be searched for simultaneously. Calling
287 [`RE2::Set#add`](https://mudge.name/re2/RE2/Set.html#add-instance_method) with
288 a regular expression will return the integer index at which it is stored within
289 the set. After all patterns have been added, the set can be compiled using
290 [`RE2::Set#compile`](https://mudge.name/re2/RE2/Set.html#compile-instance_method),
291 and then
292 [`RE2::Set#match`](https://mudge.name/re2/RE2/Set.html#match-instance_method)
293 will return an array containing the indices of all the patterns that matched.
294 [`RE2::Set#size`](https://mudge.name/re2/RE2/Set.html#size-instance_method)
295 will return the number of patterns in the set.
296
297 ```ruby
298 set = RE2::Set.new
299 set.add("abc") #=> 0
300 set.add("def") #=> 1
301 set.add("ghi") #=> 2
302 set.size #=> 3
303 set.compile #=> true
304 set.match("abcdefghi") #=> [0, 1, 2]
305 set.match("ghidefabc") #=> [2, 1, 0]
306 ```
307
308 ### Replacing and extracting
309
310 [`RE2.replace`](https://mudge.name/re2/RE2.html#replace-class_method) returns a copy of a given string with the first occurrence of a pattern replaced with a given rewrite string:
311
312 ```ruby
313 RE2.replace("hello there", "hello", "howdy") #=> "howdy there"
314 ```
315
316 The pattern can be given as either a string or an `RE2::Regexp`:
317
318 ```ruby
319 re = RE2('hel+o')
320 RE2.replace("hello there", re, "yo") #=> "yo there"
321 ```
322
323 To replace _all_ matches and not just the first, use [`RE2.global_replace`](https://mudge.name/re2/RE2.html#global_replace-class_method):
324
325 ```ruby
326 RE2.global_replace("hallo thare", "a", "e") #=> "hello there"
327 ```
328
329 To extract matches with a given rewrite string including substitutions, use [`RE2.extract`](https://mudge.name/re2/RE2.html#extract-class_method):
330
331 ```ruby
332 RE2.extract("[email protected]", '(\w+)@(\w+)', '\2-\1')
333 #=> "example-alice"
334 ```
335
336 ### Escaping
337
338 To escape all potentially meaningful regexp characters in a string, use [`RE2.escape`](https://mudge.name/re2/RE2.html#escape-class_method):
339
340 ```ruby
341 RE2.escape("1.5-2.0?") #=> "1\\.5\\-2\\.0\\?"
342 ```
343
344 ### Encoding
345
346 > [!WARNING]
347 > Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
348 > returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
349 > `RE2::Regexp` is set to `false` (any other encoding's behaviour is undefined).
350
351 For backward compatibility: re2 won't automatically convert string inputs to
352 the right encoding so this is the responsibility of the caller, e.g.
353
354 ```ruby
355 # By default, RE2 will process patterns and text as UTF-8
356 RE2(non_utf8_pattern.encode("UTF-8")).partial_match(non_utf8_text.encode("UTF-8"))
357
358 # If the :utf8 option is false, RE2 will process patterns and text as ISO-8859-1
359 RE2(non_latin1_pattern.encode("ISO-8859-1"), utf8: false).partial_match(non_latin1_text.encode("ISO-8859-1"))
360 ```
361
362 ## Requirements
363
364 This gem requires the following to run:
365
366 * [Ruby](https://www.ruby-lang.org/en/) 3.1 to 4.0
367
368 It supports the following RE2 ABI versions:
369
370 * libre2.0 (prior to release 2020-03-02) to libre2.11 (2023-07-01 to 2025-11-05)
371
372 ### Native gems
373
374 Where possible, a pre-compiled native gem will be provided for the following platforms:
375
376 * Linux
377 * `aarch64-linux`, `arm-linux`, and `x86_64-linux` (requires [glibc](https://www.gnu.org/software/libc/) 2.29+, RubyGems 3.3.22+ and Bundler 2.3.21+)
378 * [musl](https://musl.libc.org/)-based systems such as [Alpine](https://alpinelinux.org) are supported with Bundler 2.5.6+
379 * macOS 10.14+ `x86_64-darwin` and `arm64-darwin`
380 * Windows 2022+ `x64-mingw-ucrt`
381
382 ### Verifying the gems
383
384 SHA256 checksums are included in the [release notes](https://github.com/mudge/re2/releases) for each version and can be checked with `sha256sum`, e.g.
385
386 ```console
387 $ gem fetch re2 -v 2.18.0
388 Fetching re2-2.18.0-arm64-darwin.gem
389 Downloaded re2-2.18.0-arm64-darwin
390 $ sha256sum re2-2.18.0-arm64-darwin.gem
391 953063f0491420163d3484ed256fe2ff616c777ec66ee20aa5ec1a1a1fc39ff5 re2-2.18.0-arm64-darwin.gem
392 ```
393
394 [GPG](https://www.gnupg.org/) signatures are attached to each release (the assets ending in `.sig`) and can be verified if you import [our signing key `0x39AC3530070E0F75`](https://mudge.name/39AC3530070E0F75.asc) (or fetch it from a public keyserver, e.g. `gpg --keyserver keyserver.ubuntu.com --recv-key 0x39AC3530070E0F75`):
395
396 ```console
397 $ gpg --verify re2-2.18.0-arm64-darwin.gem.sig re2-2.18.0-arm64-darwin.gem
398 gpg: Signature made Sun 3 Aug 11:02:26 2025 BST
399 gpg: using RSA key 702609D9C790F45B577D7BEC39AC3530070E0F75
400 gpg: Good signature from "Paul Mucur <[email protected]>" [unknown]
401 gpg: aka "Paul Mucur <[email protected]>" [unknown]
402 gpg: WARNING: This key is not certified with a trusted signature!
403 gpg: There is no indication that the signature belongs to the owner.
404 Primary key fingerprint: 7026 09D9 C790 F45B 577D 7BEC 39AC 3530 070E 0F75
405 ```
406
407 The fingerprint should be as shown above or you can independently verify it with the ones shown in the footer of https://mudge.name.
408
409 ### Installing the `ruby` platform gem
410
411 > [!WARNING]
412 > We strongly recommend using the native gems where possible to avoid the need
413 > for compiling the C++ extension and its dependencies which will take longer
414 > and be less reliable.
415
416 If you wish to compile the gem, you will need to explicitly install the `ruby` platform gem:
417
418 ```ruby
419 # In your Gemfile with Bundler 2.3.18+
420 gem "re2", force_ruby_platform: true
421
422 # With Bundler 2.1+
423 bundle config set force_ruby_platform true
424
425 # With older versions of Bundler
426 bundle config force_ruby_platform true
427
428 # Without Bundler
429 gem install re2 --platform=ruby
430 ```
431
432 You will need a full compiler toolchain for compiling Ruby C extensions (see
433 [Nokogiri's "The Compiler
434 Toolchain"](https://nokogiri.org/tutorials/installing_nokogiri.html#appendix-a-the-compiler-toolchain))
435 plus the toolchain required for compiling the vendored version of RE2 and its
436 dependency [Abseil][] which includes [CMake](https://cmake.org), a compiler
437 with C++17 support such as [clang](http://clang.llvm.org/) 5 or
438 [gcc](https://gcc.gnu.org/) 8 and a recent version of
439 [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config/). On
440 Windows, you'll also need pkgconf 2.1.0+ to avoid [`undefined reference`
441 errors](https://github.com/pkgconf/pkgconf/issues/322) when attempting to
442 compile Abseil.
443
444 ### Using system libraries
445
446 If you already have RE2 installed, you can instruct the gem not to use its own vendored version:
447
448 ```ruby
449 gem install re2 --platform=ruby -- --enable-system-libraries
450
451 # If RE2 is not installed in /usr/local, /usr, or /opt/homebrew:
452 gem install re2 --platform=ruby -- --enable-system-libraries --with-re2-dir=/path/to/re2/prefix
453 ```
454
455 Alternatively, you can set the `RE2_USE_SYSTEM_LIBRARIES` environment variable instead of passing `--enable-system-libraries` to the `gem` command.
456
457
458 ## Thanks
459
460 * Thanks to [Jason Woods](https://github.com/driskell) who contributed the
461 original implementations of `RE2::MatchData#begin` and `RE2::MatchData#end`.
462 * Thanks to [Stefano Rivera](https://github.com/stefanor) who first contributed
463 C++11 support.
464 * Thanks to [Stan Hu](https://github.com/stanhu) for reporting a bug with empty
465 patterns and `RE2::Regexp#scan`, contributing support for libre2.11
466 (2023-07-01) and for vendoring RE2 and abseil and compiling native gems in
467 2.0.
468 * Thanks to [Sebastian Reitenbach](https://github.com/buzzdeee) for reporting
469 the deprecation and removal of the `utf8` encoding option in RE2.
470 * Thanks to [Sergio Medina](https://github.com/serch) for reporting a bug when
471 using `RE2::Scanner#scan` with an invalid regular expression.
472 * Thanks to [Pritam Baral](https://github.com/pritambaral) for contributing the
473 initial support for `RE2::Set`.
474 * Thanks to [Mike Dalessio](https://github.com/flavorjones) for reviewing the
475 precompilation of native gems in 2.0.
476 * Thanks to [Peter Zhu](https://github.com/peterzhu2118) for
477 [ruby_memcheck](https://github.com/Shopify/ruby_memcheck) and helping find
478 the memory leaks fixed in 2.1.3.
479 * Thanks to [Jean Boussier](https://github.com/byroot) for contributing the
480 switch to Ruby's `TypedData` API and the resulting garbage collection
481 improvements in 2.4.0.
482 * Thanks to [Manuel Jacob](https://github.com/manueljacob) for reporting a bug
483 when passing strings with null bytes.
484 * Thanks to [Maciej Gajewski](https://github.com/konieczkow) for helping
485 confirm issues with GC compaction and mutable strings.
486
487 ## Contact
488
489 All issues and suggestions should go to [GitHub Issues](https://github.com/mudge/re2/issues).
490
491 ## License
492
493 This library is licensed under the BSD 3-Clause License, see `LICENSE.txt`.
494
495 Copyright © 2010, Paul Mucur.
496
497 ### Dependencies
498
499 The source code of [RE2][] is distributed in the `ruby` platform gem. This code is licensed under the BSD 3-Clause License, see `LICENSE-DEPENDENCIES.txt`.
500
501 The source code of [Abseil][] is distributed in the `ruby` platform gem. This code is licensed under the Apache License 2.0, see `LICENSE-DEPENDENCIES.txt`.
502
503 [RE2]: https://github.com/google/re2
504 [Abseil]: https://abseil.io