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 (real RE2 deletes both, for pointer-stability reasons this wrapper does not share — real::regex copies cheaply). A pattern this layer cannot honor does not throw: construction always succeeds syntactically, and ok()/error()/error_code() report the rejection, exactly mirroring how RE2 itself reports a syntax error.

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.

A separate overload from the std::string_view one below, not merely a call site of it: std::string’s own conversion to std::string_view is itself user-defined, and C++ allows at most one user-defined conversion in an implicit sequence, so a lone string_view constructor would make FullMatch(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 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.

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 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 T*.

Constructed implicitly from a pointer to any supported destination type (std::string, std::string_view, bool, or an integral/floating-point type), or from nullptr to skip a group without extracting it. FullMatch/PartialMatch/Consume/FindAndConsume take these by value in a variadic pack; each successful parse writes into the pointee, a failed one (a submatch that does not convert, e.g. text into an int) 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 — a set of patterns tested together. Mirrors real RE2’s Set: buffer patterns with Add, Compile once, then Match repeatedly. Maps directly onto REAL’s native real::regex_set::which() (index-list semantics match exactly).

Anchor is synthesized by wrapping each added pattern (^(?:…)/^(?:…)$) before compiling, since real::regex_set itself 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:

true on success. false should not happen if every Add already 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 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 bool longest_match() const noexcept#

Whether to search for the longest match instead of the first. Honored for PartialMatch (via real::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.

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#