对字符串迭代器使用boost::regex_search()

Using boost::regex_search() with string iterators

本文关键字:regex search boost 字符串 迭代器      更新时间:2023-10-16

我试图得到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
}

我对regex_search()的调用触发了智能感知,并且编译失败("没有'regex_search'的实例匹配参数列表")。

我试图调用的重载是:

template <class BidirectionalIterator,
    class Allocator, class charT, class traits>
bool regex_search(BidirectionalIterator first, BidirectionalIterator last,
    match_results<BidirectionalIterator, Allocator>& m,
    const basic_regex<charT, traits>& e,
    match_flag_type flags = match_default );

这似乎符合我的调用很好。

任何想法都是赞赏的!以及做这类事情的其他方法。我最终想做的是像这样分割字符串:

"0.11,0.22;0.33,0.444;0.555,0.666"

转换为可解析的浮点字符串组成列表。

在任何其他regex包中,它都很简单-通过像"(?:([0-9.]+)[;,]?)+"这样的表达式运行它,捕获的组将包含结果。

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

你是正确的,将test声明为const std::string将修复它,因为test.end()现在将返回const_iterator,而不是iterator

或者,你可以这样做:do:

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
}

如果你有c++ 11可用,你也可以使用新的std::string::cend成员:

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
}

好了,我明白了。如果搜索的字符串被声明为"const",则该方法被正确找到。例如:

const std::string test = "1234567890";