如何在 C++ 中获取正则表达式的底层字符串?

Use*_*645 2 c++ regex string c++17

我有一个字符串,想检查这个字符串是否与指定的正则表达式匹配。如果不是这种情况,我想向用户返回一个警告,说string xyz does not match regex abc.

示例代码:

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
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为两者std::string(rgx)"some string " + rgx + " more string"给出了一个错误。

std::basic_regex似乎也没有提供一种方法来检索描述它的底层字符串(请参阅cppreference)。我错过了什么?

我正在使用 C++17。

Nat*_*ica 5

std::regex一旦构造好,它就没有提供从中获取字符串的方法。解决这个问题的一种方法是将正则表达式和字符串包装在一个对象中,以便您可以将它们一起传递。那看起来像

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; }
};
Run Code Online (Sandbox Code Playgroud)

然后你会在你的代码中使用它

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
}
Run Code Online (Sandbox Code Playgroud)

您可以改为使用makestrregex转换运算符,但一个问题是许多正则表达式库使用函数模板,并且在类型推导期间没有进行转换,因此您必须显式转换,这比调用成员函数更冗长。