如何获得与 C++11 或 Boost 匹配的正则表达式长度
How to get length of regex match with C++11 or Boost?
是否有一个库函数可用于获取第一个正则表达式匹配的长度(如果没有匹配,则返回 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 == 6
和b == 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
并返回其长度。
相关文章:
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 为什么 Boost:正则表达式没有按预期找到所有结果?
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用 boost::regex (c++) 比较两个正则表达式
- 我的 Boost 正则表达式与任何内容都不匹配
- 使用boost正则表达式时出现shared_ptr错误
- Boost正则表达式:链接时未定义的引用
- 如何使用perl样式内存正则表达式与Boost库匹配
- 如何获得与 C++11 或 Boost 匹配的正则表达式长度
- 递归匹配与 boost 正则表达式库
- 提高Boost正则表达式的速度或在C++中使用PCRE
- boost正则表达式中的命名捕获/组列表
- 使用Boost替换正则表达式
- 关于正则表达式与Boost的逻辑AND和OR匹配的说明
- 将 C++11 正则表达式与 gcc 4.8.2 一起使用时会出现奇怪的结果(但适用于 Boost 正则表达式)
- 使用 Boost 的 C++ 中的正则表达式
- Boost::qt Creator中的正则表达式
- 如何使 Boost.Spirit.Lex 令牌值成为匹配序列的子字符串(最好通过正则表达式匹配组)
- Boost.Test 使用正则表达式测试文件内容
- 使用 Boost::regex 进行正则表达式组匹配