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 by real::regex — linear-time, ReDoS-safe.

Copyable and movable, where RE2 deletes both (real::regex copies cheaply). A rejected pattern does not throw: ok(), error() and error_code() report it, as RE2 does.

Public Functions

inline RE2(const char *pattern)#

Compiles pattern with default options. Implicit, like real RE2’s own pattern constructors — so FullMatch(text, "a.*b", &arg) builds a temporary RE2 in place.

Parameters:

pattern – [in] The pattern text (NUL-terminated).

inline RE2(const std::string &pattern)#

Compiles pattern with default options. Implicit; see the const char* overload.

Not mergeable into the std::string_view overload: a std::string would then need two user-defined conversions to become an RE2, and FullMatch(text, some_string, &arg) would stop compiling.

Parameters:

pattern – [in] The pattern text.

inline RE2(std::string_view pattern)#

Compiles pattern with default options. Implicit; see the const char* overload.

Parameters:

pattern – [in] The pattern text.

inline RE2(std::string_view pattern, const Options &options)#

Compiles pattern with options.

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 RE2 was 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::NoError if ok().

Returns:

The category, ErrorCode::NoError when construction succeeded.

inline const Options &options() const noexcept#

The construction options this RE2 was 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 0 if !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 text must match re.

Template Parameters:

Args – Destination pointer types (deduced), one per submatch extracted.

Parameters:
  • text – [in] The subject text.

  • re – [in] The pattern (an RE2, or a pattern text implicitly converted to one).

  • args – [out] Destinations for the first sizeof...(Args) capturing groups (see Arg); pass none to just test for a match.

Returns:

true on a full match with every args extraction succeeding.

template<typename ...Args>
static inline bool PartialMatch(std::string_view text, const RE2 &re, Args&&... args)#

Unanchored match: re must match some substring of text.

Template Parameters:

Args – Destination pointer types (deduced), one per submatch extracted.

Parameters:
  • text – [in] The subject text.

  • re – [in] The pattern (an RE2, or a pattern text implicitly converted to one).

  • args – [out] Destinations for the first sizeof...(Args) capturing groups (see Arg); pass none to just test for a match.

Returns:

true on a match with every args extraction 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:
  • input – [inout] The subject text; shrunk from the front on a successful match.

  • re – [in] The pattern (an RE2, or a pattern text implicitly converted to one).

  • args – [out] Destinations for the first sizeof...(Args) capturing groups (see Arg).

Returns:

true on a match with every args extraction 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:
  • input – [inout] The subject text; shrunk from the front on a successful match.

  • re – [in] The pattern (an RE2, or a pattern text implicitly converted to one).

  • args – [out] Destinations for the first sizeof...(Args) capturing groups (see Arg).

Returns:

true on a match with every args extraction succeeding.

static inline bool Replace(std::string *str, const RE2 &re, std::string_view rewrite)#

Replaces the first match of re in *str with rewrite.

rewrite may 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:

true if a match was found and rewrite was well-formed.

static inline int GlobalReplace(std::string *str, const RE2 &re, std::string_view rewrite)#

Replaces every non-overlapping match of re in *str with rewrite.

rewrite may 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* over aa gives one replacement); other empty matches are replaced (a* over bbb gives #b#b#b#).

Parameters:
  • str – [inout] The subject; rewritten in place only if every match’s rewrite expansion 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 (0 if none, or if rewrite was malformed).

static inline std::string QuoteMeta(std::string_view unquoted)#

Escapes every regex metacharacter in unquoted so the result matches it literally.

Parameters:

unquoted – [in] The raw text.

Returns:

The escaped pattern text.

class Arg#

A type-erased destination for one captured submatch, built implicitly from a pointer to std::string, std::string_view, bool or an arithmetic type, or from nullptr to skip the group. A submatch that does not convert fails the whole match call.

Public Functions

inline constexpr Arg() noexcept#

Default-constructs a no-op Arg (same as Arg(nullptr)).

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 Arg is 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 by parser).

  • parser – [in] The parser called on parse.

class Set#

RE2::Set: Add patterns, Compile once, then Match repeatedly, on real::regex_set::which(). The anchor is applied by wrapping each pattern, real::regex_set being 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:

true on success; false when the members together exceed max_mem, as RE2’s own Compile fails (each member was already probe-compiled by Add).

inline bool Match(std::string_view text, std::vector<int> *v) const#

Tests text against 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:

true if at least one member matched.

class Options#

RE2-compatible construction options. Mirrors real RE2’s RE2::Options field-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 Options is 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 true by default, as RE2’s does; logging itself is opt-in here (see set_log_errors), and RE2::ok()/RE2::error() report errors either way.

Returns:

The setting.

inline void set_log_errors(bool value) noexcept#

Sets log_errors. Only an explicit set_log_errors(true) arms RE2’s stderr message on a failed compile; set_log_errors(false) disarms it.

Parameters:

value – [in] The new setting.

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#