User12547645
User12547645

Reputation: 8477

How to get the underlying string of a regular expression in C++?

I have a string and want to check if this string matches a specified regex. If that is not the case I would like to return a warning to the user that says string xyz does not match regex abc.

Example code:

std::string func(std::basic_regex rgx, std::string str)
{
    // do stuff 1
    if (!std::regex_match(str, rgx))
    {
        return "String " + str + " does not match the pattern " + std::string(rgx);
    }
    // do stuff 2
}

This does not work, since both std::string(rgx) and "some string " + rgx + " more string" gives an error.

Also std::basic_regex does not seem to provide a method to retrieve the underlying string that describes it (see cppreference). What did I miss?

I am using C++17.

Upvotes: 2

Views: 442

Answers (1)

NathanOliver
NathanOliver

Reputation: 180945

std::regex doesn't provide a way to get the string from it once it has been constructed. One way to get around that is to wrap the regex and the string together in a object so you can pass them together. That would look like

class my_regex
{
    std::string str;
    std::regex regex;
public:
    my_regex(const std::string& regex_str) : str(regex_str), regex(regex_str) {}
    const std::string& str() const { return str; }
    std::regex& regex() { return regex; }
};

and then you would use it in your code like

std::string func(my_regex rgx, std::string str)
{
    // do stuff 1
    if (!std::regex_match(str, rgx.regex()))
    {
        return "String " + str + " does not match the pattern " + rgx.str();
    }
    // do stuff 2
}

You could make str and regex conversion operators instead but an issue with that is that a lot of the regex library uses function templates and no conversion is done during type deduction so you would have to explicitly cast, which is more verbose then just calling a member function.

Upvotes: 5

Related Questions