gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:46:17 26 4
gpt4 key购买 nike

是否有库函数可用于获取第一个正则表达式匹配的长度(如果没有匹配则返回 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 正则表达式,但我发现 Mingw GCC 4.7.1 的 STL 正则表达式功能存在问题:

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

最佳答案

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

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com