我知道从std :: string获取正则表达式匹配的两种方法,但是我不知道如何使用它们各自的偏移来获得所有匹配.
#include <string> #include <iostream> #include <regex> int main() { using namespace std; string s = "123 apples 456 oranges 789 bananas oranges bananas"; regex r = regex("[a-z]+"); const sregex_token_iterator end; // here I kNow how to get all occurences // but don't kNow how to get starting offset of each one for (sregex_token_iterator i(s.cbegin(),s.cend(),r); i != end; ++i) { cout << *i << endl; } cout << "====" << endl; // and here I kNow how to get position // but the code is finding only first match smatch m; regex_search ( s,m,r ); for (unsigned i=0; i< m.size(); ++i) { cout << m.position(i) << endl; cout << m[i] << endl; } }
解决方法
首先,为什么令牌迭代器?您没有任何标记的子表达式来迭代.
其次,position()是匹配的成员函数,因此:
#include <string> #include <iostream> #include <regex> int main() { std::string s = "123 apples 456 oranges 789 bananas oranges bananas"; std::regex r("[a-z]+"); for(std::sregex_iterator i = std::sregex_iterator(s.begin(),s.end(),r); i != std::sregex_iterator(); ++i ) { std::smatch m = *i; std::cout << m.str() << " at position " << m.position() << '\n'; } }
住在coliru:http://coliru.stacked-crooked.com/a/492643ca2b6c5dac
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。