RE2 compatibility#
Synopsis#
real::compat::re2::RE2 – Google’s RE2 surface on the linear engine,
header-only and zero-dependency. The statics take typed Arg outputs, the
instance keeps RE2’s no-exception contract (ok()), and RE2::Set is
the multi-pattern which-matched. Migration, divergences and limits live in
the RE2 drop-in – this page is the object reference.
Interface#
-
class RE2#
RE2-compatible drop-in for
RE2. Backed byreal::regex— linear-time, ReDoS-safe.Copyable and movable, where RE2 deletes both (
real::regexcopies cheaply). A rejected pattern does not throw:ok(),error()anderror_code()report it, as RE2 does.Public Functions
-
inline RE2(const char *pattern)#
Compiles
patternwith default options. Implicit, like real RE2’s own pattern constructors — soFullMatch(text, "a.*b", &arg)builds a temporaryRE2in place.- Parameters:
pattern – [in] The pattern text (NUL-terminated).
-
inline RE2(const std::string &pattern)#
Compiles
patternwith default options. Implicit; see theconst char*overload.Not mergeable into the
std::string_viewoverload: astd::stringwould then need two user-defined conversions to become anRE2, andFullMatch(text, some_string, &arg)would stop compiling.- Parameters:
pattern – [in] The pattern text.
-
inline RE2(std::string_view pattern)#
Compiles
patternwith default options. Implicit; see theconst char*overload.- Parameters:
pattern – [in] The pattern text.
-
inline RE2(std::string_view pattern, const Options &options)#
Compiles
patternwithoptions.- Parameters:
pattern – [in] The pattern text.
options – [in] The construction options.
-
inline bool ok() const noexcept#
Whether construction succeeded (
error_code() == ErrorCode::NoError).- Returns:
Whether the pattern compiled.
-
inline const std::string &pattern() const noexcept#
The pattern text this
RE2was built from.- Returns:
The pattern, valid as long as this object is alive.
-
inline const std::string &error() const noexcept#
The rejection reason, or an empty string if
ok().- Returns:
The message, empty when construction succeeded.
-
inline ErrorCode error_code() const noexcept#
The coarse rejection category, or
ErrorCode::NoErrorifok().- Returns:
The category,
ErrorCode::NoErrorwhen construction succeeded.
-
inline const Options &options() const noexcept#
The construction options this
RE2was built with.- Returns:
The options, valid as long as this object is alive.
-
inline int NumberOfCapturingGroups() const noexcept#
The number of capturing groups (excluding group 0), or
0if!ok().- Returns:
The capturing-group count.
Public Static Functions
-
template<typename ...Args>
static inline bool FullMatch(std::string_view text, const RE2 &re, Args&&... args)# Anchored-both match: the whole
textmust matchre.- Template Parameters:
Args – Destination pointer types (deduced), one per submatch extracted.
- Parameters:
- Returns:
trueon a full match with everyargsextraction succeeding.
-
template<typename ...Args>
static inline bool PartialMatch(std::string_view text, const RE2 &re, Args&&... args)# Unanchored match:
remust match some substring oftext.- Template Parameters:
Args – Destination pointer types (deduced), one per submatch extracted.
- Parameters:
- Returns:
trueon a match with everyargsextraction succeeding.
-
template<typename ...Args>
static inline bool Consume(std::string_view *input, const RE2 &re, Args&&... args)# Anchored-start match against
*input; on success, removes the matched prefix from*input.- Template Parameters:
Args – Destination pointer types (deduced), one per submatch extracted.
- Parameters:
- Returns:
trueon a match with everyargsextraction succeeding.
-
template<typename ...Args>
static inline bool FindAndConsume(std::string_view *input, const RE2 &re, Args&&... args)# Unanchored match anywhere in
*input; on success, removes everything up to and including the match from*input.- Template Parameters:
Args – Destination pointer types (deduced), one per submatch extracted.
- Parameters:
- Returns:
trueon a match with everyargsextraction succeeding.
-
static inline bool Replace(std::string *str, const RE2 &re, std::string_view rewrite)#
Replaces the first match of
rein*strwithrewrite.rewritemay reference groups RE2-style:\0(whole match),\1…\9,\\for a literal backslash.- Parameters:
str – [inout] The subject; rewritten in place only on success.
re – [in] The pattern (an
RE2, or a pattern text implicitly converted to one).rewrite – [in] The replacement template.
- Returns:
trueif a match was found andrewritewas well-formed.
-
static inline int GlobalReplace(std::string *str, const RE2 &re, std::string_view rewrite)#
Replaces every non-overlapping match of
rein*strwithrewrite.rewritemay reference groups RE2-style:\0(whole match),\1…\9,\\for a literal backslash.As in RE2, an empty match starting where the previous match ended is skipped (
a*overaagives one replacement); other empty matches are replaced (a*overbbbgives#b#b#b#).- Parameters:
str – [inout] The subject; rewritten in place only if every match’s
rewriteexpansion succeeds.re – [in] The pattern (an
RE2, or a pattern text implicitly converted to one).rewrite – [in] The replacement template.
- Returns:
The number of replacements made (
0if none, or ifrewritewas malformed).
-
static inline std::string QuoteMeta(std::string_view unquoted)#
Escapes every regex metacharacter in
unquotedso the result matches it literally.- Parameters:
unquoted – [in] The raw text.
- Returns:
The escaped pattern text.
-
inline RE2(const char *pattern)#
-
class Arg#
A type-erased destination for one captured submatch, built implicitly from a pointer to
std::string,std::string_view,boolor an arithmetic type, or fromnullptrto skip the group. A submatch that does not convert fails the whole match call.Public Functions
-
inline constexpr Arg(std::nullptr_t) noexcept#
From
nullptr— skips this submatch (always “succeeds”, writes nothing).
-
template<typename T>
inline Arg(T *dest) noexcept# From a destination pointer — the common case (
&i,&s,&d, …).- Template Parameters:
T – The pointee type:
std::string,std::string_view,bool, or an integral/floating-point type.- Parameters:
dest – [in] The destination; must outlive the call this
Argis passed to.
-
inline constexpr Arg(void *dest, Parser parser) noexcept#
From an explicit destination and parser — the escape hatch for a custom radix or a caller-supplied type not covered by the
T*constructor.- Parameters:
dest – [in] The destination (opaque to
Arg; interpreted only byparser).parser – [in] The parser called on
parse.
-
inline constexpr Arg(std::nullptr_t) noexcept#
-
class Set#
RE2::Set:Addpatterns,Compileonce, thenMatchrepeatedly, onreal::regex_set::which(). The anchor is applied by wrapping each pattern,real::regex_setbeing unanchored.Public Functions
-
inline Set(const Options &options, Anchor anchor)#
Starts an empty set.
- Parameters:
options – [in] The options applied to every member pattern.
anchor – [in] The anchor mode every member is matched with.
-
inline int Add(std::string_view pattern, std::string *error)#
Buffers one pattern (validated immediately, like real RE2’s
Add).- Parameters:
pattern – [in] The pattern text.
error – [out] If non-null and the pattern is rejected, set to a human-readable reason.
- Returns:
The pattern’s index (matches
Match’s output indices) on success, or-1.
-
inline bool Compile()#
Compiles every buffered pattern into one
real::regex_set.- Returns:
trueon success;falsewhen the members together exceedmax_mem, as RE2’s ownCompilefails (each member was already probe-compiled byAdd).
-
inline bool Match(std::string_view text, std::vector<int> *v) const#
Tests
textagainst every compiled member.- Parameters:
text – [in] The subject text.
v – [out] If non-null, cleared and filled with the indices of every matching member.
- Returns:
trueif at least one member matched.
-
inline Set(const Options &options, Anchor anchor)#
-
class Options#
RE2-compatible construction options. Mirrors real RE2’s
RE2::Optionsfield-for-field (names, defaults); see the file-level doc comment for which fields this layer honors.Public Functions
-
Options() = default#
Default options: UTF-8, leftmost-first, case-sensitive, every RE2 default kept.
-
inline Options(CannedOptions canned)#
One of RE2’s canned option sets. Implicit, as RE2’s own, so a canned set passes where
Optionsis taken.- Parameters:
canned – [in] The set.
-
inline std::int64_t max_mem() const noexcept#
The compiled-pattern budget, as RE2’s: a program past two thirds of it fails with
ErrorPatternTooLarge(at most 1, a 100 000-instruction bound applies instead). Counted in REAL’s program bytes (12 per instruction against RE2’s 8, no shared prefixes), so a lowered budget does not reject exactly what RE2 rejects; the default rejects nothing REAL compiles.- Returns:
The budget, in bytes.
-
inline void set_max_mem(std::int64_t value) noexcept#
Sets
max_mem.- Parameters:
value – [in] The new budget, in bytes.
-
inline bool longest_match() const noexcept#
Whether to search for the longest match instead of the first; honored by every unanchored search.
- Returns:
Whether leftmost-longest semantics are selected.
-
inline void set_longest_match(bool value) noexcept#
Sets
longest_match.- Parameters:
value – [in] The new setting.
-
inline bool log_errors() const noexcept#
Whether compile errors are logged. Reads
trueby default, as RE2’s does; logging itself is opt-in here (see set_log_errors), andRE2::ok()/RE2::error()report errors either way.- Returns:
The setting.
-
Options() = default#
Complexity#
The same engine as basic_regex: every accepted pattern matches in
guaranteed linear time – O(len(text)) – and never backtracks
(ReDoS-safe). A construct this layer cannot honor is a clean
ok() == false, never a silent fallback.
Example#
Compiled and run by the example-check gate on every push:
using real::compat::re2::RE2;
// The RE2 statics, with typed Arg extraction -- one output per capture group.
std::string user;
std::string host;
const bool hit = RE2::PartialMatch("info@example.com", R"((\w+)@(\w+))", &user, &host);
std::cout << hit << ": " << user << " at " << host << "\n"; // 1: info at example
// The instance surface: ok() is the no-exception contract.
const RE2 number {R"(\d+)"};
std::cout << number.ok() << "\n"; // 1
See also#
Migration, divergences, benchmarks: the RE2 drop-in.
The native engine behind it: basic_regex.
Native multi-pattern which-matched: regex_set.