You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用boost::split分割字符串时如何忽略{}内的下划线分隔符

字符串分割需求说明

需要以下划线_作为分隔符对字符串做分割,规则约束:

  • 大括号{}内部的下划线不识别为分隔符,仅大括号外部的下划线作为有效分割标记
  • 待分割的目标字符串如下:
{[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]} 
  • 预期分割后得到3个独立数据项:
{[Data1]_[Data2]_[Data3]}
{[Val1]_[Val2]}
{[ID1]_[ID2]_[ID3]}
现有实现问题

当前基于boost::split的实现会无差别识别所有下划线为分隔符,会把大括号内部的下划线也做分割,无法满足规则,现有代码如下:

std::vector<std::string> commandSplitSemiColon;
boost::split(commandSplitSemiColon, stdstrCommand, boost::is_any_of("_"), 
boost::token_compress_on);
调整方案

boost::split本身不支持基于上下文的分隔符判定,不需要强行适配boost的split接口,直接通过单次遍历+括号深度计数的方式实现即可,逻辑简单可控:

#include <vector>
#include <string>
#include <boost/algorithm/string/trim.hpp>

std::vector<std::string> splitValidCommand(const std::string& stdstrCommand) {
    std::vector<std::string> result;
    std::string currentSeg;
    int braceDepth = 0;

    for (char ch : stdstrCommand) {
        if (ch == '{') {
            braceDepth++;
            currentSeg += ch;
        } else if (ch == '}') {
            braceDepth--;
            currentSeg += ch;
        } else if (ch == '_' && braceDepth == 0) {
            // 仅大括号外部的下划线触发分割
            boost::trim(currentSeg);
            if (!currentSeg.empty()) {
                result.push_back(currentSeg);
            }
            currentSeg.clear();
        } else {
            currentSeg += ch;
        }
    }

    // 追加最后一个分割片段
    boost::trim(currentSeg);
    if (!currentSeg.empty()) {
        result.push_back(currentSeg);
    }

    return result;
}

逻辑说明

  • 用braceDepth变量记录当前大括号的嵌套层级,初始值为0,代表当前处于大括号外部
  • 逐字符遍历原字符串:
    • 遇到左大括号{时层级计数+1,字符追加到当前片段缓存
    • 遇到右大括号}时层级计数-1,字符追加到当前片段缓存
    • 遇到下划线时,只有层级计数为0(不在任何大括号内部)才触发分割:把当前缓存的片段去除首尾空白后存入结果集,清空缓存准备收集下一个片段
    • 其余字符直接追加到当前片段缓存
  • 遍历完成后,把缓存中剩余的最后一个片段处理后存入结果集即可
  • 如果业务场景存在大括号不配对的异常输入,可以在遍历结束后增加braceDepth == 0的校验,按需做异常处理

内容的提问来源于stack exchange,提问作者shomit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 06:51:06