C++ std::正则表达式未按预期匹配

c++ std::regex doesn't match as expected

本文关键字:std 正则表达式 C++      更新时间:2023-10-16

我试图实现一个简单的字符串测试方法使用c++ std::regex,在MS vc++ 2012。

const std::string str = "1.0.0.0029.443";
if ( std::regex_match( str, std::regex( "\.0\d+" ) ) )
    std::cout << "matched." << std::endl;

我猜代码会匹配"。但是,它根本不匹配。

使用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';
}

std::regex_match报告精确匹配,即整个输入字符串必须匹配正则表达式。

匹配子序列,使用std::regex_search

为了确保您的regex匹配完整字符串,您需要这样做:

^(?:d+.)*d+$

翻译成

if ( std::regex_match( str, std::regex( "^(?:\d+\.)*\d+$" ) ) )
    std::cout << "matched." << std::endl;

需要锚^$的开头和结尾,否则您可能会在BANANA_0.1.12AND_APPLE中间匹配字符串