【问题标题】:std::regex_match giving false match results when rvalues parameters are passed当传递右值参数时,std::regex_match 给出错误的匹配结果
【发布时间】:2012-06-22 04:48:31
【问题描述】:

希望有人能回答这个问题。这是一些示例代码。

namespace std {
#ifdef UNICODE
typedef wstring tstring;
typedef wstringstream tstringstream;
#define tcout std::wcout
#else
typedef string tstring;
typedef stringstream tstringstream;
#define tcout std::cout
#endif
typedef regex_iterator<std::tstring::const_iterator> TRegexIterator;
}

std::TRegexIterator::regex_type nPattern(_TEXT("-?[0-9]+(\\.[0-9]+)?((e|E)(\\+|-)[0-9]+)?"));
std::match_results<std::tstring::const_iterator> theMatches;
std::tstring test(_TEXT("-1.323E-23"));

tcout << _TEXT("Lvalue target string") << std::endl;
if (std::regex_match(test, theMatches, nPattern))
{
    for (auto i= 0; i < theMatches.size(); ++i)
        tcout << theMatches[i] << std::endl;
}

tcout << _TEXT("Rvalue target string") << std::endl;
if (std::regex_match(std::tstring(_TEXT("-1.323E-23")), theMatches, nPattern))
{
    for (auto i= 0; i < theMatches.size(); ++i)
        tcout << theMatches[i] << std::endl;
}

好的,我遇到的问题是第一个带有右值目标字符串的匹配结果是
“ 1.323E-23”(是的,有一个起始空格)而不是预期的“-1.323E-23”。我认为这是因为“std::match_results”存储指针而不是数据,但在这种情况下,为什么“std::regex_match”的第一个参数是“const std::string&”? (这是我从 Intellisense 验证的)。 “std::string&”似乎更合适。 我正在使用 VS11 beta C++ 编译器。

【问题讨论】:

    标签: c++ visual-c++ c++11


    【解决方案1】:

    是的,

    这是因为“std::match_results”存储的是指针而不是数据。

    例如,测试以下代码:

    tcout << _TEXT("Lvalue target string") << std::endl;
    if (std::regex_match(test, theMatches, nPattern))
    {
        test = _TEXT(""); // change 'test' to invalidate 'theMatches' pointers
        for (auto i= 0; i < theMatches.size(); ++i)
            tcout << theMatches[i] << std::endl; // MEMORY ERROR!!!
    }
    

    但是,你为什么相信

    “std::string&”似乎比“const std::string&”更合适。

    在我看来“const std::string&”似乎更合适,因为“std::regex_match”不需要改变这个参数。

    【讨论】:

    • 谢谢。是的,“const”限定符是对用户的一种保证,即“std::regex_match”不会更改第一个参数。但是同样的“const”限定符允许将右值传递给“std::regex_match”。当第一个参数超出范围时,这会导致匹配失效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多