是否有库函数可用于获取第一个正则表达式匹配的长度(如果没有匹配则返回 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();
}
Boost效果很好。我也尝试过 STL 正则表达式,但我发现 STL 正则表达式功能在 mingw GCC 4.7.1 中存在错误:
最佳答案
如 match_results 所示boost 文档中,有: length(n)
返回指定匹配的长度。
另一种方法是:获取匹配的字符串
并返回其长度。
关于c++ - 如何使用 C++11 或 Boost 获取正则表达式匹配的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868755/