C++按分隔符拆分字符串并将分隔符保留在结果中

标签 c++ regex delimiter string-split

我正在寻找一种在 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/

相关文章:

c++函数重载问题

regex - 从 url (www.google.com=google) 匹配域名

bash - Echo 将我的制表符更改为空格

Excel:在最后一个/之前复制规则

python - 在 csv.writer 中添加空格作为分隔符

c++ - 使用最少的代码行读取 C++ 中的表格数字数据

c++ - 就 size_t 而言, "size of the largest possible object on the target platform"是什么

regex - 第一个单词以未列入黑名单的特定字符开头

regex - .awk 正则表达式中的转义字符

c++ - 从 DLL 写入控制台