我正在寻找一种在 C++ 中使用正则表达式将字符串拆分为多个分隔符的方法,但不会在输出中丢失分隔符,保持分隔符与拆分部分的顺序,例如:
输入
aaa,bbb.ccc,ddd-eee;
输出
aaa , bbb . ccc , ddd - eee ;
我已经找到了一些解决方案,但都是在 C# 或 java 中,寻找一些 C++ 解决方案,最好不使用 Boost。
最佳答案
您可以在 regex_iterator
的示例之上构建您的解决方案.例如,如果您知道分隔符是逗号、句点、分号和连字符,则可以使用捕获分隔符或一系列非分隔符的正则表达式:
([.,;-]|[^.,;-]+)
将其放入示例代码中,您最终会得到 something like this :
#include <iostream>
#include <string>
#include <regex>
int main ()
{
// the following two lines are edited; the remainder are directly from the reference.
std::string s ("aaa,bbb.ccc,ddd-eee;");
std::regex e ("([.,;-]|[^.,;-]+)"); // matches delimiters or consecutive non-delimiters
std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), e );
std::regex_iterator<std::string::iterator> rend;
while (rit!=rend) {
std::cout << rit->str() << std::endl;
++rit;
}
return 0;
}
尝试替换为您喜欢的任何其他正则表达式。
关于C++按分隔符拆分字符串并将分隔符保留在结果中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27706443/