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

如何在Scala中将含括号的字符串分割为指定List?

解决方案

可以通过遍历字符串+状态标记的方式实现需求,核心是跟踪是否处于括号内部,仅当不在括号内时才按逗号分割,同时处理片段前后的空格。

实现思路

  • 用in_parentheses标记当前是否处于括号内部,初始值为False
  • 用current_part临时拼接正在处理的片段
  • 逐个遍历字符串字符:
    • 遇到(时,标记进入括号状态并将字符加入临时片段
    • 遇到)时,标记退出括号状态并将字符加入临时片段
    • 遇到逗号且不在括号内时:将临时片段去空格后加入结果列表,再清空临时片段
    • 其他字符直接加入临时片段
  • 遍历结束后,处理最后一个临时片段并加入结果列表

代码示例(Python)

def split_with_parentheses(s):
    result = []
    current_part = []
    in_parentheses = False
    for char in s:
        if char == '(':
            in_parentheses = True
            current_part.append(char)
        elif char == ')':
            in_parentheses = False
            current_part.append(char)
        elif char == ',' and not in_parentheses:
            part = ''.join(current_part).strip()
            if part:
                result.append(part)
            current_part = []
        else:
            current_part.append(char)
    # 处理最后一个片段
    final_part = ''.join(current_part).strip()
    if final_part:
        result.append(final_part)
    return result

# 测试
str_input = "one,two,(three,four), five"
print(split_with_parentheses(str_input))
# 输出: ['one', 'two', '(three,four)', 'five']

补充说明

  • 如果需要支持嵌套括号,只需把in_parentheses改成计数器:遇到(加1,遇到)减1,仅当计数器为0时才按逗号分割
  • 代码中的strip()确保了片段前后无多余空格,匹配需求格式
  • 加入了空片段过滤逻辑,避免分割结果中出现空字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:45:35