可能重复:
C++11正则表达式无法匹配
以前我使用的是boost::regex
来做一些事情,现在我想用std::regex
来做一些新东西,但我注意到以下不一致性——所以问题是哪一个是正确的?
#include <iostream>
#include <regex>
#include <string>
#include <boost/regex.hpp>
void test(std::string prefix, std::string str)
{
std::string pat = prefix + "\\.\\*.*?";
std::cout << "Input : [" << str << "]" << std::endl;
std::cout << "Pattern : [" << pat << "]" << std::endl;
{
std::regex r(pat);
if (std::regex_match(str, r))
std::cout << "std::regex_match: true" << std::endl;
else
std::cout << "std::regex_match: false" << std::endl;
if (std::regex_search(str, r))
std::cout << "std::regex_search: true" << std::endl;
else
std::cout << "std::regex_search: false" << std::endl;
}
{
boost::regex r(pat);
if (boost::regex_match(str, r))
std::cout << "boost::regex_match: true" << std::endl;
else
std::cout << "boost::regex_match: false" << std::endl;
if (boost::regex_search(str, r))
std::cout << "boost::regex_search: true" << std::endl;
else
std::cout << "boost::regex_search: false" << std::endl;
}
}
int main(void)
{
test("FOO", "FOO.*");
test("FOO", "FOO.*.*.*.*");
}
对于我来说(gcc 4.7.2,-std=c++11,boost:1.51),我看到如下内容:
Input : [FOO.*]
Pattern : [FOO\.\*.*?]
std::regex_match: false
std::regex_search: false
boost::regex_match: true
boost::regex_search: true
Input : [FOO.*.*.*.*]
Pattern : [FOO\.\*.*?]
std::regex_match: false
std::regex_search: false
boost::regex_match: true
boost::regex_search: true
如果我将模式更改为贪婪模式(
.*
),那么我会看到:Input : [FOO.*]
Pattern : [FOO\.\*.*]
std::regex_match: true
std::regex_search: false
boost::regex_match: true
boost::regex_search: true
Input : [FOO.*.*.*.*]
Pattern : [FOO\.\*.*]
std::regex_match: true
std::regex_search: false
boost::regex_match: true
boost::regex_search: true
该相信哪个?我猜测这里应该是boost
正确的?
std::string pat = prefix + "\\.\\*.*?";
,因此如果prefix
是FOO.*
,那么pat
必须最终成为FOO.*\.\*.*?
,而不是FOO.*?
。 - j_random_hacker