我需要拆分一系列格式如下面两个字符串的字符串:
<verb> sigh <adverb> ; portend like <object> ; die <adverb> ;
<start> The <object> <verb> tonight. ;
到一个向量中,其中第一个非限制符(例如:"<verb>"
)是向量的第一个元素,然后字符串的其余部分被分号分解为元素。因此,当我完成时,第一个示例字符串应该像这样分解:
newvec.at(0)= <verb>
newvec.at(1) = sigh <adverb>
newvec.at(2) = portend like <object>
newvect.at(3) = die <adverb>
第二个示例字符串应该生成向量:
newvec.at(0) = <start>
newvec.at(1)=The <object> <verb> tonight.
我提供了以下函数,使用正则表达式作为分隔符将字符串分解为向量,并且在我以前需要它时工作正常,但是如果我甚至在这种情况下我很难弄清楚如何使用它可以。
/**
* Splits the input string based on the (string) regular expression.
*
* @param input the string to split.
* @param regex a string for the regular expression to use to split.
* @param delim if true, then the regex chars will be returned in the split,
* if false, the regex chars are removed.
* @return a vector of strings that is the input string split based on the
* given regular expression.
*/
vector<string> split(const string &input, const string ®ex, bool delim = true) {
std::regex re(regex);
std::sregex_token_iterator first, last;
if (delim) {
first = sregex_token_iterator{input.begin(), input.end(), re};
} else {
// the -1 removes the delimiter
first = sregex_token_iterator{input.begin(), input.end(), re, -1};
}
return vector<string>(first, last);
}
在我的函数中调用new_vec = split(ex_string, ";", false)
会将字符串拆分为基于分号的向量(并删除分号),但我不确定如何使第一个非限制器成为第一个元素向量。任何帮助将不胜感激。
答案 0 :(得分:0)
以下是我的尝试:它正在工作但不整洁。你也可以使用smatch_iterator,我相信它会很简单
vector<string> splitt(string str) {
smatch sm;
vector<string> vec;
regex re1("([^ ;]*?>)| ; (.*?>)| (.*?>)");
while(regex_search(str,sm,re1)) {
for(int i=1;i<sm.size();i++) {
if(sm[i]!="")
vec.push_back(sm[i]);
}
str=sm.suffix().str();
}
return vec;
}
答案 1 :(得分:0)