对字符串迭代器使用boost::regex_search()
Using boost::regex_search() with string iterators
我试图得到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::iterator
和std::string::const_iterator
),并且由于regex_search
是模板函数,因此不允许从iterator
到const_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";
相关文章:
- 此模式的C++RegEx
- QTableview Search
- LeetCode 1011.Binary Search,C++和Python的想法相同,但输出不同
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 二叉搜索树 - 实现"search"函数
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 使用Regex解析cpp中的字符串并创建映射
- C++:如何用split查找单词?Regex
- 在VC2015U3上,std::regex比boost::regex慢得多
- 是否有更有效的方法来生成日期的REGEX字符串
- 在C++中使用带有regex的捕获组
- 将std::regex设置为静态的好主意吗
- 为什么Regex(c++)需要指数时间
- std::regex and dual ABI
- C++11 std::regex后备选项
- 以不同的方式替换每一项,regex c++
- 使用 boost::regex (c++) 比较两个正则表达式
- 如何理解boost::regex的哪一部分未能匹配/search