如何迭代std :: string中的所有正则表达式匹配以及它们在c 11 st
发布时间:2020-12-14 06:02:07 所属栏目:百科 来源:网络整理
导读:我知道从std :: string获取正则表达式匹配的两种方法,但是我不知道如何使用它们各自的偏移来获得所有匹配. #include string#include iostream#include regexint main() { using namespace std; string s = "123 apples 456 oranges 789 bananas oranges bana
我知道从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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |