假设我们有一个字符串:"((0.2,0), (1.5,0)) A1 ABC p"
。我想把它分成像这样的逻辑单元:在分隔符上使用特定限制的分割字符串
((0.2,0), (1.5,0))
A1
ABC
p
即,按照要求前一个字符不是逗号的空格拆分字符串。 是否可以使用regex
作为解决方案?
更新:我已经试过这样:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string s = "((0.2,0), (1.5,0)) A1 ABC p";
std::regex re("[^, ]*\\(, *[^, ]*\\)*"); // as suggested in the updated answers
std::sregex_token_iterator
p(s.begin(), s.end(), re, -1);
std::sregex_token_iterator end;
while (p != end)
std::cout << *p++ << std::endl;
}
结果是:((0.2,0), (1.5,0)) A1 ABC p
解决方案:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string s = "((0.2,0), (1.5,0)) A1 ABC p";
std::regex re("[^, ]*(, *[^, ]*)*");
std::regex_token_iterator<std::string::iterator> p(s.begin(), s.end(), re);
std::regex_token_iterator<std::string::iterator> end;
while (p != end)
std::cout << *p++ << std::endl;
}
输出:
((0.2,0), (1.5,0))
A1
ABC
p
@TobySpeight,感谢您的纠正我刚更新了一个代码片段的问题 –
这还不完整(它缺少一个' main()',一件事),但它越来越近了。当你有编译的东西时,请更新。 –