CPP 中带有多个分隔符的分割线

split line in cpp with multiple delimiter

本文关键字:分隔符 分割线 CPP      更新时间:2023-10-16

我想按<=>=>的外观拆分每一行 所以我有 2 个分隔符,每个分隔符都有不止一个字符

  string example="A + B => C + D";
  vector <string> leftRight;
  boost::algorithm::split_regex( leftRight, example, boost::is_any_of( " <=> +| => " ));

我的预期结果是这样的:

leftright[0]= A+B
leftright[1]= C+D

那么,让我们看看boost::algorithm::split_regex .在最后一个参数之前,您做得很好。该函数期望 boost::regex 作为最后一个参数,而boost::is_any_of不提供其中一个参数。

您的用例的合理正则表达式如下所示:

boost::regex r("(<=>)|(=>)");

如果我们把所有这些放在一起:

#include <vector>
#include <string>
#include <iostream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
int main() {
    std::string example="A + B => C + D";
    std::vector <std::string> leftRight;
    boost::regex r("(<=>)|(=>)");
    boost::algorithm::split_regex(leftRight, example, r);
    for (int i=0; i<leftRight.size(); ++i)
        std::cout << """ << leftRight[i] << ""n";
}

我们得到的输出为:

"A + B "
" C + D"