c++ - 如何使用 C++11 或 Boost 获取正则表达式匹配的长度?

标签 c++ regex boost c++11

是否有库函数可用于获取第一个正则表达式匹配的长度(如果没有匹配则返回 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();
}

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

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

最佳答案

match_results 所示boost 文档中,有: length(n) 返回指定匹配的长度。

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

关于c++ - 如何使用 C++11 或 Boost 获取正则表达式匹配的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868755/

相关文章:

Ruby 正则表达式匹配除非用\转义

c++ - 维护一个 std::set<boost::shared_ptr>

c++ - 如何访问 "boost::function"中的类实例(对象)指针?

c++ - 如何将 Ncurses 添加到 Visual Studio 2017 中的项目?

使用 OpenGL 的 C++ 绘图数组

c++ - unordered_map 用于堆管理系统。是否可以进行无碰撞设置?

c++ - 重写 operator>> 用于 Strings 类

regex - git 使用什么风格的正则表达式

python - 是否可以根据字段类型(例如 TextControl、TextareaControl)来选择表单字段?

c++ - 如何获取有关您的应用占用多少 RAM 的信息?