lundi 22 juin 2015

extracting original regex pattern from std::regex

I have a function which is attempting to match a given string against a given regex pattern. If it does not match, it should create a string indicating such occurrence and include the regex pattern it failed and the content of the string. Something similar to such:

bool validate_content(const std::string & str, const std::regex & pattern, std::vector<std::string> & errors)
{
    std::smatch matches;
    if ( false == std::regex_match(str, pattern, matches) )
    {
        std::stringstream error_str;
        // error_str << "Pattern match failure: " << pattern << ", content: " << str;
        errors.push_back(error_str.str());
        return false;
    }
    return true;
}

However as you can see, the commented-out line presents a challenge: is it possible to recover the original pattern of the regex object?

There is obviously a workaround of providing the original pattern string (instead of or alongside) the regex object and then using that. But I would have of course preferred to not need to include the extra work to either recreate the regex object every time this function is called (biting cost in reparsing the pattern every time the function is called) or to pass the regex pattern along with the regex object (prone to typos and errors unless I provide a wrapper which does that for me, which is not as convenient).

I'm using GCC 4.9.2 on Ubuntu 14.04.

Aucun commentaire:

Enregistrer un commentaire