Overview / Text & language

regex

Automata-based regular expressions with no backtracking, always linear in the length of the input. UTF-8 text and patterns, with RE2 and Perl semantics.

Always compiled: part of the core build.Include #include <ethereal/cpp/regex/regex_inc.hpp>C layer

regex_inc.hpp

#include <ethereal/cpp/regex/regex_inc.hpp>

Aggregate entry point of the Regex module.

Linear time regular expressions (automata, no backtracking).

regex.hpp

#include <ethereal/cpp/regex/regex.hpp>

Linear time regular expressions.

Automata, no backtracking. The time of a search is linear in the size of the text, always: '(a+)+b' against a hundred thousand 'a' takes milliseconds. The price: there are no backreferences ('\1'), no lookaround ('(?=', '(?<='), no atomic groups, possessive quantifiers, conditionals or recursion. Compile rejects them with the name of the construct and its offset in the pattern, so whoever needs them knows right away.

Compile once, search many times. Compiling is the cold path (it allocates, under a ceiling). Searching allocates nothing. A CRegex can be shared between threads: the searches use its scratch area one at a time. To search in parallel, each thread uses its own CRegexScratch.

The semantics are those of RE2 and Perl: the leftmost match, and inside it the first alternative (greedy quantifiers try more first). Text and pattern are UTF-8: '.' and the classes match a whole code point, and an invalid UTF-8 byte in the text matches none of them. Positions are in bytes.

In ASCII mode (bAsciiOnly) everything is bytes, the pattern too: '.' and the classes match one byte, '\xHH' is that byte, and a non ASCII character written in the pattern is its bytes, one by one ('[\xC3\xA9]' is "C3 or A9"). No '\p' and no Unicode case folding.

Supported: literals, '.', classes ('[a-z]', '[^...]', '[[:alpha:]]', '\d \w \s' and their negations), anchors ('^ $ \A \z \b \B'), alternation, groups ('(...)', '(?:...)', '(?<name>...)', '(?P<name>...)'), quantifiers ('* + ? {n} {n,} {n,m}', greedy and lazy), escapes ('\t \n \r \f \v \a \e \xHH \x{HHHH}'), options in the pattern ('(?i) (?m) (?s) (?x) (?U)' and '(?i:...)'), and the Unicode classes ('\p{L}', '\p{Greek}', '\p{Script=Greek}', '\P{...}') when the Text module is compiled in.

Without '(?m)', '$' is only the end of the text (as in RE2. In Perl it also matches before a final '\n'). With '(?m)', '^' and '$' also match next to each '\n'.

enum

ERegexStatus

Ethereal::Regex#
C++
enum class   ERegexStatus : std::uint8_t
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  The pattern is malformed. SRegexError tells where and why.
    eSyntax,

    /// @brief  A construct that linear time does not allow. See SRegexError::eConstruct.
    eUnsupported,

    /// @brief  The program goes over the memory ceiling of the options.
    eTooBig,

    /// @brief  The pattern is not UTF-8 (outside ASCII mode).
    eInvalidUtf8,

    /// @brief  '\p{...}' (or Unicode case folding) without the Text module compiled in.
    eNeedsText,

    /// @brief  The output buffer is too small.
    eBufferTooSmall,

    /// @brief  An invalid argument.
    eInvalidArgument,

    /// @brief  An empty CRegex.
    eNotCompiled,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///          ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,
};

Result of the regex calls.

function

StatusName

Ethereal::Regex#
const char * StatusName( ERegexStatus e ) noexcept;

Name of a status, for logs.

e
The status.
A static string.
enum

EConstruct

Ethereal::Regex#
C++
enum class   EConstruct : std::uint8_t
{
    /// @brief  No construct.
    eNone = 0,

    /// @brief  '\1', '\k<name>'.
    eBackreference,

    /// @brief  '(?=', '(?!'.
    eLookahead,

    /// @brief  '(?<=', '(?<!'.
    eLookbehind,

    /// @brief  '(?>'.
    eAtomicGroup,

    /// @brief  '*+', '++', '?+', '{n,m}+'.
    ePossessive,

    /// @brief  '(?('.
    eConditional,

    /// @brief  '(?R)', '(?1)', '(?&name)'.
    eRecursion,
};

The rejected constructs, by name.

function

ConstructName

Ethereal::Regex#
const char * ConstructName( EConstruct e ) noexcept;

Name of a construct, for logs.

e
The construct.
A static string.
struct

SRegexError

Ethereal::Regex#
C++
struct   SRegexError
{
    /// @brief  The error status.
    ERegexStatus        eStatus = ERegexStatus::eOk;

    /// @brief  The rejected construct, with eUnsupported.
    EConstruct            eConstruct = EConstruct::eNone;

    /// @brief  Byte of the pattern where the problem is.
    std::size_t            uOffset = 0;

    /// @brief  Static message, in English.
    const char *        pMessage = "";
};

Details of a compile error.

struct

SRegexOptions

Ethereal::Regex#
C++
struct   SRegexOptions
{
    /// @brief  ASCII and Unicode. Unicode simple case folding needs the Text module.
    bool            bCaseInsensitive = false;

    /// @brief  '^' and '$' also match next to each '\n'.
    bool            bMultiline = false;

    /// @brief  '.' also matches '\n'.
    bool            bDotAll = false;

    /// @brief  Quantifiers are lazy by default.
    bool            bUngreedy = false;

    /// @brief  Spaces and '#...' in the pattern are ignored.
    bool            bExtended = false;

    /// @brief  No Unicode: bytes, ASCII '\w' and '\b'. Faster.
    bool            bAsciiOnly = false;

    /// @brief  Ceiling of the compiled program and its scratch area. Going over it is eTooBig.
    std::size_t        uMaxProgramBytes = 1u << 22;

    /// @brief  Cache of the deterministic automata, per scratch area (fixed, allocated at
    ///             compile time).
    ///
    /// @details  0 is automatic: 1 KB per program instruction, between 32 KB and 1 MB,
    ///               which is plenty for the common patterns (tens of states). A pattern
    ///               with many states (e.g. '(a|b)*a(a|b){12}') that fills it stays correct
    ///               and linear, through the PikeVM. More cache here gives it back the speed
    ///               of the automaton.
    std::size_t        uDfaCacheBytes = 0;
};

Compile options. The pattern can also set most of them inline.

struct

SMatch

Ethereal::Regex#
C++
struct   SMatch
{
    /// @brief  The whole match.
    std::string_view                Whole;

    /// @brief  The groups, in caller space. May be empty.
    std::span< std::string_view >    Groups;
};

A match: views into the searched text.

Groups points to space of the caller (1 + GroupCount() views, view 0 is the whole match). A group that did not take part is a null view (data() == nullptr). A group that matched empty has a valid data().

class

CRegexScratch

Ethereal::Regex#

A search scratch area, for a thread that searches in parallel with others on the same CRegex.

class CRegexScratch

Created, with its memory allocated, once. See CRegex::CreateScratch.

constructor

CRegexScratch

#
CRegexScratch() noexcept = default;

Builds an empty scratch area.

constructor

CRegexScratch

#
CRegexScratch( CRegexScratch && o ) noexcept;

Takes the scratch area of o, which is left empty.

operator

operator=

#
CRegexScratch & operator=( CRegexScratch && o ) noexcept;

Frees this scratch area and takes the one of o, which is left empty.

class

CRegex

Ethereal::Regex#

A compiled regular expression.

class CRegex
constructor

CRegex

#
CRegex() noexcept = default;

Builds an empty regex. Call Compile before use.

constructor

CRegex

#
CRegex( CRegex && o ) noexcept;

Takes the program of o, which is left empty.

operator

operator=

#
CRegex & operator=( CRegex && o ) noexcept;

Frees this program and takes the one of o, which is left empty.

function

Compile

#
static ERegexStatus Compile( std::string_view sPattern, const SRegexOptions & Options, CRegex * pOut, SRegexError * pError = nullptr ) noexcept;

Compiles a pattern.

The cold path: it allocates, under the ceiling of the options. On error pOut is left empty and pError tells what happened.

sPattern
The pattern, UTF-8 (or bytes in ASCII mode).
Options
Compile options.
pOut
Receives the compiled regex.
pError
Receives the error details. May be null.
eOk, or the error status. eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

IsCompiled

#
bool IsCompiled() const noexcept

true when a program is compiled.

function

IsMatch

#
bool IsMatch( std::string_view s ) const noexcept;

Is there any match? No captures: the fastest path.

s
The text.
true when the pattern matches somewhere in s.
function

Find

#
bool Find( std::string_view s, SMatch * pOut, std::size_t uStart = 0 ) const noexcept;

The first match that starts at uStart or after it.

s
The text.
pOut
Receives the match. Its Groups say how many groups to fill. May be null.
uStart
Byte where the search starts.
true when a match was found.
function

FullMatch

#
bool FullMatch( std::string_view s, SMatch * pOut ) const noexcept;

Does the whole text match?

s
The text.
pOut
Receives the match. May be null.
true when the pattern matches all of s.
function

FindAll

#
std::size_t FindAll( std::string_view s, std::span< std::string_view > Out ) const noexcept;

All matches, without overlaps.

Only Whole. The groups come from CMatchIterator. An empty match right at the end of the previous one does not count (as in Rust): 'a*' in "baaa" gives "" and "aaa". The same rule holds for Replace, Split and the iterator.

s
The text.
Out
Receives the matches that fit.
The number of matches, which may be more than fits in Out.
function

Replace

#
ERegexStatus Replace( std::string_view sIn, std::string_view sReplacement, std::span< char > Out, std::size_t * pWritten, bool bAll ) const noexcept;

Replaces the first match, or all of them.

In sReplacement, '$0'..'$9', '${n}', '${name}' and '$$'. A group that did not take part gives empty text. Any other '$', or a group the pattern does not have, is eInvalidArgument.

sIn
The text.
sReplacement
The replacement template.
Out
Receives the result.
pWritten
Receives the size of the whole result. May be null.
bAll
true replaces all matches, false only the first.
eOk, or eBufferTooSmall when the result does not fit in Out (the part that fits is written).
function

Split

#
std::size_t Split( std::string_view s, std::span< std::string_view > Out ) const noexcept;

The pieces between the matches.

s
The text.
Out
Receives the pieces that fit.
The number of pieces.
function

IsMatch

#
bool IsMatch( std::string_view s, CRegexScratch & Scratch ) const noexcept;

Same as IsMatch, with the scratch area of Scratch (without locking the CRegex).

s
The text.
Scratch
A scratch area made by CreateScratch on this CRegex.
true when the pattern matches somewhere in s.
function

Find

#
bool Find( std::string_view s, SMatch * pOut, std::size_t uStart, CRegexScratch & Scratch ) const noexcept;

Same as Find, with the scratch area of Scratch (without locking the CRegex).

s
The text.
pOut
Receives the match. May be null.
uStart
Byte where the search starts.
Scratch
A scratch area made by CreateScratch on this CRegex.
true when a match was found.
function

CreateScratch

#
ERegexStatus CreateScratch( CRegexScratch * pOut ) const noexcept;

Prepares a scratch area to search this CRegex in parallel.

Allocates once.

pOut
Receives the scratch area.
eOk, eInvalidArgument, eNotCompiled or eTooBig (out of memory).
function

GroupCount

#
std::size_t GroupCount() const noexcept;

Number of capture groups, not counting the whole match.

function

GroupIndex

#
int GroupIndex( std::string_view sName ) const noexcept;

Index of the group with this name, or -1.

sName
Group name.
function

ProgramSize

#
std::size_t ProgramSize() const noexcept;

Memory of the compiled program and its scratch area, in bytes, without the automata cache. This is what uMaxProgramBytes limits.

class

CMatchIterator

Ethereal::Regex#

The matches one by one, with the groups, without storing them all.

class CMatchIterator

Without a scratch area each match locks the internal area of the CRegex. With a CRegexScratch made for the same CRegex nothing is locked, and threads can iterate in parallel, each with its own area.

C++
std::string_view aG[ 4 ];
CMatchIterator It( Re, sText, aG );
SMatch M;
while( It.Next( &M ) ) { ... }
constructor

CMatchIterator

#
CMatchIterator( const CRegex & Re, std::string_view s, std::span< std::string_view > Groups ) noexcept : m_pRe( &Re ), m_s( s ), m_Groups( Groups )

Starts an iteration over s.

Re
The compiled regex. Must outlive the iterator.
s
The text. Must outlive the iterator.
Groups
Caller space for the groups of each match.
constructor

CMatchIterator

#
CMatchIterator( const CRegex & Re, std::string_view s, std::span< std::string_view > Groups, CRegexScratch & Scratch ) noexcept : m_pRe( &Re ), m_s( s ), m_Groups( Groups ), m_pScratch( &Scratch )

Starts an iteration over s that searches in Scratch, without locking.

A scratch area made for another CRegex is not used: the iteration falls back to the internal area, locked, as Find does.

Re
The compiled regex. Must outlive the iterator.
s
The text. Must outlive the iterator.
Groups
Caller space for the groups of each match.
Scratch
A scratch area made by CreateScratch on Re. Must outlive the iterator.
function

Next

#
bool Next( SMatch * pOut ) noexcept;

The next match.

pOut
Receives the match. May be null.
false when there are no more matches.
function

Seek

#
void Seek( std::size_t uPos ) noexcept

Goes on from uPos, as if the previous match had ended there.

An empty match right at uPos does not count (the empty match rule). For a caller that shortens a match before going on. A position past the end of the text ends the iteration.

uPos
Byte of the text where the next search starts.