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 (real RE2 deletes both, for pointer-stability reasons this wrapper does not share —
real::regexcopies cheaply). A pattern this layer cannot honor does not throw: construction always succeeds syntactically, andok()/error()/error_code()report the rejection, exactly mirroring how RE2 itself reports a syntax error.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.A separate overload from the
std::string_viewone below, not merely a call site of it:std::string’s own conversion tostd::string_viewis itself user-defined, and C++ allows at most one user-defined conversion in an implicit sequence, so a lonestring_viewconstructor would makeFullMatch(text, some_std_string, &arg)stop compiling implicitly (real RE2 keeps the same three-constructor split for the same reason).- 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.Empty-match policy matches real RE2’s
GlobalReplace: a zero-width match whose start equals the end of the previous (accepted) match is skipped — it abuts the prior match and must not produce a second rewrite (e.g.a*on"aa"yields one replacement, not two). Legitimate non-abutting empty matches (e.g.a*on"bbb"→#b#b#b#) are still applied.- 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
T*.Constructed implicitly from a pointer to any supported destination type (
std::string,std::string_view,bool, or an integral/floating-point type), or fromnullptrto skip a group without extracting it.FullMatch/PartialMatch/Consume/FindAndConsumetake these by value in a variadic pack; each successfulparsewrites into the pointee, a failed one (a submatch that does not convert, e.g. text into anint) 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— a set of patterns tested together. Mirrors real RE2’sSet: buffer patterns withAdd,Compileonce, thenMatchrepeatedly. Maps directly onto REAL’s nativereal::regex_set::which()(index-list semantics match exactly).Anchoris synthesized by wrapping each added pattern (^(?:…)/^(?:…)$) before compiling, sincereal::regex_setitself is natively unanchored-search only — documented here rather than silently assumed.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.falseshould not happen if everyAddalready succeeded (each pattern was already probe-compiled individually); kept for API fidelity.
-
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 bool longest_match() const noexcept#
Whether to search for the longest match instead of the first. Honored for
PartialMatch(viareal::regex::search_longest()); see the file-level doc comment.- Returns:
Whether leftmost-longest semantics are selected.
-
inline void set_longest_match(bool value) noexcept#
Sets
longest_match.- Parameters:
value – [in] The new 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.