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

Python如何实现仅按引号外的分隔符分割字符串(无库)

问题

给定字符串 '"abc"+ h abc "abch"',要求仅将引号外部的子串abc作为分隔符拆分字符串,禁止使用任何标准库模块、第三方库,纯Python实现,预期拆分结果为 ['"abc"+ h ', '"abch"']。

实现方案

核心逻辑是遍历字符串时实时标记当前是否处于引号包裹区间,只在引号外匹配分隔符做切割,避免误切引号内的内容。

def split_ignore_quoted(input_str, delimiter, quote_mark='"'):
    result = []
    delimiter_len = len(delimiter)
    str_len = len(input_str)
    inside_quote = False
    split_start = 0
    idx = 0
    while idx < str_len:
        # 遇到引号切换内外状态
        if input_str[idx] == quote_mark:
            inside_quote = not inside_quote
            idx += 1
            continue
        # 仅在引号外校验分隔符匹配
        if not inside_quote:
            if input_str[idx:idx+delimiter_len] == delimiter:
                result.append(input_str[split_start:idx])
                split_start = idx + delimiter_len
                idx += delimiter_len
                continue
        idx += 1
    # 追加最后一段剩余内容
    result.append(input_str[split_start:])
    return result

# 测试用例
test_s = '"abc"+ h abc"abch"'
print(split_ignore_quoted(test_s, 'abc'))

运行代码即可得到符合要求的拆分结果。

逻辑说明

  • 用布尔变量inside_quote跟踪当前遍历位置是否在双引号包裹范围内,每遇到一个双引号就翻转该状态
  • 仅当inside_quote为False(即处于引号外部)时,才检查当前位置是否匹配分隔符,匹配则执行切割,更新下一段的起始切割位置
  • 全程仅使用Python基础语法、内置字符串操作,无任何外部依赖,时间复杂度为O(n),性能稳定
  • 函数支持自定义分隔符、引号标记,可复用到同类“忽略引号内内容拆分”的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 18:22:10