如何获得与 C++11 或 Boost 匹配的正则表达式长度

How to get length of regex match with C++11 or Boost?

本文关键字:正则表达式 Boost 何获得 C++11      更新时间:2023-10-16

是否有一个库函数可用于获取第一个正则表达式匹配的长度(如果没有匹配,则返回 0)?

所以我需要一些与此类似的功能:

int length_of_match(const std::string& s, const std::string& rx)
{
    ...
}
例如,

可以这样轻松使用:

int a = length_of_match("number = 10", "^[a-zA-z][a-zA-z0-9]*");
int b = length_of_match(" = 10", "^[a-zA-z][a-zA-z0-9]*");

在那之后a == 6b == 0

编辑:

感谢您的回复,这对我帮助很大。我的问题的解决方案是:

int length_of_match(const std::string& s, const std::string& rx)
{
    boost::regex expr(rx);
    boost::match_results<std::string::const_iterator> what;
    if (!regex_search(s.begin(), s.end(), what, expr)) return 0;
    return what.length();
}

提升效果很好。我也尝试了 STL 正则表达式,但我发现 STL 正则表达式功能在 mingw GCC 4.7.1 中存在错误:

is-gcc4-7-buggy-about-regular-expressions

与match_results提升文档一样,有: length(n) 返回指定匹配项的长度。

另一种方法是:获取匹配的string并返回其长度。