我尝试在 MS VC++ 2012 中使用 c++ std::regex 实现一个简单的字符串测试方法。
const std::string str = "1.0.0.0029.443";
if ( std::regex_match( str, std::regex( "\\.0\\d+" ) ) )
std::cout << "matched." << std::endl;
我猜代码会匹配给定字符串的“.0029”部分。但是,它根本不匹配。 我在 http://regex101.com/ 上试过了它奏效了。
最佳答案
使用std::regex_search
而不是返回您的子匹配项。
const std::string str = "1.0.0.0029.443";
std::regex rgx("(\\.0[0-9]+)");
std::smatch match;
if (std::regex_search(str.begin(), str.end(), match, rgx)) {
std::cout << match[1] << '\n';
}
关于c++ std::regex 与预期不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319103/