将boost :: regex_search()与字符串迭代器一起使用

时间:2013-03-24 23:45:39

标签: c++ regex boost-regex

我正在尝试使用boost :: regex来为我提供搜索字符串中出现的所有模式。认为这样的事情很简单,但是让它加强和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()的调用导致了intellisense,并且无法编译(“没有'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"

进入浮点字符串的组成列表,然后我可以解析它。

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

2 个答案:

答案 0 :(得分:3)

问题实际上是你混合迭代器类型(std::string::iteratorstd::string::const_iterator,而regex_search是模板函数,隐式转换从iterator到{ {1}}是不允许的。

您是正确的,将const_iterator声明为test可以解决问题,因为const std::string现在会返回test.end(),而不是const_iterator

或者,您可以这样做:

iterator

如果你有C ++ 11可用,你也可以使用新的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::cend

答案 1 :(得分:0)

好的,想出这个。如果搜索到的字符串被声明为“const”,则可以正确找到该方法。 E.g:

const std::string test = "1234567890";
相关问题