【发布时间】:2014-07-24 00:32:24
【问题描述】:
我想像这样拆分一个字符串
“this1245is@g$0,therhsuidthing345”
使用下面的单词列表
{“this”, “is”, “the”, “thing”}
进入这个列表
{“this”, “1245”, “is”, “@g$0,”, “the”, “rhsuid”, “thing”, “345”}
// ^--------------^---------------^------------------^-- these were the delimiters
分隔符在要分割的字符串中允许出现多次,可以使用正则表达式来完成
优先级是分隔符在数组中出现的顺序
我正在开发的平台不支持 Boost 库
更新
这是我目前拥有的
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("this1245is@g$0,therhsuidthing345");
std::string delimiters[] = {"this", "is", "the", "thing"};
for (int i=0; i<4; i++) {
std::string delimiter = "(" + delimiters[i] + ")(.*)";
std::regex e (delimiter); // matches words beginning by the i-th delimiter
// default constructor = end-of-sequence:
std::sregex_token_iterator rend;
std::cout << "1st and 2nd submatches:";
int submatches[] = { 1, 2 };
std::sregex_token_iterator c ( s.begin(), s.end(), e, submatches );
while (c!=rend) std::cout << " [" << *c++ << "]";
std::cout << std::endl;
}
return 0;
}
输出:
1st and 2nd submatches:[this][x1245fisA@g$0,therhsuidthing345]
1st and 2nd submatches:[is][x1245fisA@g$0,therhsuidthing345]
1st and 2nd submatches:[the][rhsuidthing345]
1st and 2nd submatches:[thing][345]
我想我需要做一些递归的东西来调用每次迭代
【问题讨论】:
-
你试过什么?什么地方出了错?你在哪里卡住了?您尝试过搜索什么,为什么它不适合您?
-
您是按找到的第一个单词、识别单词的最大字母集合还是其他什么?
-
@ThomasMatthews 我不太明白你的意思,但是你能不能看看更新后的问题,也许有你想要的
-
匹配“is”优先于匹配“this”。你真正想要什么行为?
-
@jxh 是的,优先顺序是分隔符出现在分隔符数组中的顺序