Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用boost::regex_search()和字符串迭代器_C++_Regex_Boost Regex - Fatal编程技术网

C++ 使用boost::regex_search()和字符串迭代器

C++ 使用boost::regex_search()和字符串迭代器,c++,regex,boost-regex,C++,Regex,Boost Regex,我试图让boost::regex提供搜索字符串中出现的所有模式。本以为这样的事情会很简单,但让boost和STL在一切之上添加10个模板模糊化元层:) 我最近尝试使用regex_search(),但不幸的是,我的调用似乎与任何重载都不匹配。下面是一个超级精炼的示例: std::string test = "1234567890"; boost::regex testPattern( "\\d" ); boost::match_results<std::string::const_itera

我试图让boost::regex提供搜索字符串中出现的所有模式。本以为这样的事情会很简单,但让boost和STL在一切之上添加10个模板模糊化元层:)

我最近尝试使用regex_search(),但不幸的是,我的调用似乎与任何重载都不匹配。下面是一个超级精炼的示例:

std::string test = "1234567890";
boost::regex testPattern( "\\d" );
boost::match_results<std::string::const_iterator> testMatches;
std::string::const_iterator startPos = test.begin();
while( regex_search( startPos, test.end(), testMatches, testPattern ) ) {
    // Do stuff: record match value, increment start position
}
进入一个浮动字符串的组成列表,然后我可以解析它


在任何其他正则表达式包中,它都很简单——通过一个类似“(?:([0-9.]+)[;,]?)+”的表达式运行它,捕获的组将包含结果

好的,我想出来了。如果搜索的字符串声明为“const”,则正确找到该方法。例如:

const std::string test = "1234567890";

问题实际上是您混合了迭代器类型(
std::string::iterator
std::string::const_iterator
),并且由于
regex_search
是一个模板函数,因此不允许从
iterator
隐式转换为
const_iterator

test
声明为
const std::string
将修复它是正确的,因为
test.end()
现在将返回一个
const\u迭代器,而不是
迭代器

或者,您可以执行以下操作:

std::string test = "1234567890";
boost::regex testPattern( "\\d" );
boost::match_results<std::string::const_iterator> testMatches;
std::string::const_iterator startPos = test.begin();
std::string::const_iterator endPos = test.end();
while( regex_search( startPos, endPos, testMatches, testPattern ) ) {
    // Do stuff: record match value, increment start position
}

很酷,谢谢-我会将此标记为答案,它很好地解释了所发生的事情。很高兴您发现它很有用。根据我个人的经验,跟踪这些“不兼容”迭代器问题可能会令人沮丧,尤其是当代码看起来正确时。我有时会将此错误的一种形式用作面试问题。
const std::string test = "1234567890";
std::string test = "1234567890";
boost::regex testPattern( "\\d" );
boost::match_results<std::string::const_iterator> testMatches;
std::string::const_iterator startPos = test.begin();
std::string::const_iterator endPos = test.end();
while( regex_search( startPos, endPos, testMatches, testPattern ) ) {
    // Do stuff: record match value, increment start position
}
std::string test = "1234567890";
boost::regex testPattern( "\\d" );
boost::match_results<std::string::const_iterator> testMatches;
std::string::const_iterator startPos = test.begin();
while( regex_search( startPos, test.cend(), testMatches, testPattern ) ) {
    // Do stuff: record match value, increment start position
}