Jon Cage Jon Cage - 1 month ago 11
C++ Question

Why doesn't boost regex '.{2}' match '??'

I'm trying to match some chunks if interesting data within a data stream.

There should be a leading

<
then four alphanumeric characters, two characters of checksum (or
??
if no shecksum was specified) and a trailing
>
.

If the last two characters are alphanumeric, the following code works as expected. If they're
??
though it fails.

// Set up a pre-populated data buffer as an example
std::string haystack = "Fli<data??>bble";

// Set up the regex
static const boost::regex e("<\\w{4}.{2}>");
std::string::const_iterator start, end;
start = haystack.begin();
end = haystack.end();
boost::match_flag_type flags = boost::match_default;

// Try and find something of interest in the buffer
boost::match_results<std::string::const_iterator> what;
bool succeeded = regex_search(start, end, what, e, flags); // <-- returns false


I've not spotted anything in the documentation which suggests this should be the case (all but NULL and newline should be match AIUI).

So what have I missed?

Answer

Because ??> is a trigraph, it will be converted to }, Your code is equivalence with:

// Set up a pre-populated data buffer as an example
std::string haystack = "Fli<data}bble";

// Set up the regex
static const boost::regex e("<\\w{4}.{2}>");
std::string::const_iterator start, end;
start = haystack.begin();
end = haystack.end();
boost::match_flag_type flags = boost::match_default;

// Try and find something of interest in the buffer
boost::match_results<std::string::const_iterator> what;
bool succeeded = regex_search(start, end, what, e, flags); // <-- returns false

You can change to this, note: I use std::regex which is likely the same:

std::string haystack = "Fli<data?" "?>bble";

DEMO