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

如何给嵌套括号内的所有内容加引号并转换为标题大小写格式

可行实现方案

采用栈深度标记+内容缓存的思路单次遍历字符串即可完成处理,无需正则替换,时间复杂度为O(n),执行效率较高,完整实现如下:

def wrap_values_within_group(s: str, delimiter_group='()'):
    start_char, end_char = delimiter_group
    res = []
    depth = 0
    in_bracket_buf = ''
    
    for c in s:
        if c == start_char:
            # 处理此前缓存的括号内文本
            if depth > 0 and in_bracket_buf:
                res.append(in_bracket_buf.title())
                in_bracket_buf = ''
            res.append(f'{start_char}"')
            depth += 1
        elif c == end_char:
            # 处理当前缓存的括号内文本
            if in_bracket_buf:
                res.append(in_bracket_buf.title())
                in_bracket_buf = ''
            res.append(f'"{end_char}')
            depth -= 1
        else:
            if depth == 0:
                # 括号外文本直接保留
                res.append(c)
            else:
                # 括号内文本先缓存
                in_bracket_buf += c
    # 兼容未闭合括号的异常场景,可根据需求调整
    if in_bracket_buf and depth > 0:
        res.append(in_bracket_buf.title())
    return ''.join(res)

测试验证

# 简单场景测试
print(wrap_values_within_group('hello(world)'))
# 输出:hello("World")

# 嵌套括号场景测试
print(wrap_values_within_group('hi (hello(world(a test)))'))
# 输出:hi ("Hello("World("A Test")")")

内容的提问来源于stack exchange,提问作者Wizard.Ritvik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:45:02