【发布时间】:2016-09-26 13:41:07
【问题描述】:
假设我们有一个字符串:"((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,感谢您的纠正。我刚刚通过输入代码 sn-p 更新了问题。
-
这还不完整(一方面它缺少
main()),但它越来越接近了。当你有可以编译的东西时,请更新。