2
我想使用Boost的正则表达式库将包含标签和数字的字符串分隔为标记。例如'abc1def002g30'
将被分成{'abc','1','def','002','g','30'}
。我修改Boost文档中给出拿出此代码example:使用Boost-Regex将字符串解析为字符和数字
#include <iostream>
#include <boost/regex.hpp>
using namespace std;
int main(int argc,char **argv){
string s,str;
int count;
do{
count=0;
if(argc == 1)
{
cout << "Enter text to split (or \"quit\" to exit): ";
getline(cin, s);
if(s == "quit") break;
}
else
s = "This is a string of tokens";
boost::regex re("[0-9]+|[a-z]+");
boost::sregex_token_iterator i(s.begin(), s.end(), re, 0);
boost::sregex_token_iterator j;
while(i != j)
{
str=*i;
cout << str << endl;
count++;
i++;
}
cout << "There were " << count << " tokens found." << endl;
}while(argc == 1);
return 0;
}
存储在count
令牌的数量是正确的。但是,*it
只包含一个空字符串,因此不会打印任何内容。任何猜测我做错了什么?
编辑:根据下面建议的修复,我修改了代码,现在它工作正常。
谢谢,我应该更加关注那个submatch参数的作用。 – John 2011-05-24 20:15:46
没问题 - 请检查它是否为有效的答案,如果没有,请在此处跟进。玩的开心! – holtavolt 2011-05-24 20:31:03