【问题标题】:C++ spliting string by delimiters and keeping the delimiters in resultC++ 通过分隔符拆分字符串并将分隔符保留在结果中
【发布时间】:2015-02-26 16:14:27
【问题描述】:

我正在寻找一种在 C++ 中使用正则表达式将字符串拆分为多个分隔符的方法,但不会丢失输出中的分隔符,保持分隔符与拆分部分的顺序,例如:

输入

aaa,bbb.ccc,ddd-eee;

输出

aaa,bbb。 ccc,ddd-eee;

我已经找到了一些解决方案,但都是在 C# 或 java 中,正在寻找一些 C++ 解决方案,最好不使用 Boost。

【问题讨论】:

    标签: c++ regex delimiter string-split


    【解决方案1】:

    对于您的情况,根据单词边界 \b 拆分您的输入字符串,除了第一个字符串之外,您将获得所需的输出。

    (?!^)\b
    

    DEMO

    (?<=\W)(?!$)|(?!^)(?=\W)
    

    DEMO

    • (?&lt;=\W)(?!$) 匹配非单词字符旁边的边界,但不匹配最后出现的边界。

    • |

    • (?!^)(?=\W) 匹配后跟非单词字符的边界,但开头的字符除外。

    如有必要,再转义一次反斜杠。

    【讨论】:

    • 由于某种原因,这些对我不起作用,未处理的异常错误。尝试添加额外的反斜杠,没有帮助。我正在使用 VS2013。
    【解决方案2】:

    您可以在 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;
    }
    

    尝试替换为您喜欢的任何其他正则表达式。

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2022-11-03
      相关资源
      最近更新 更多