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

技术问询:如何从字符串中移除最后一处()及其内部内容

移除字符串中最后一处()及其内部内容的解决方案

嘿,我完全懂你的需求——之前的代码会把所有()及其内容都删掉,但你只需要移除最后出现的那一组对吧?我给你两种场景下的解决方案,分别对应普通无嵌套的括号和有嵌套括号的情况:

一、普通无嵌套括号场景(括号内没有其他())

这种情况用正则表达式就能轻松搞定,核心思路是利用正则的贪婪匹配特性,让表达式先匹配到最后一个(之前的所有内容,再匹配最后一组()及其内部的内容,最后替换成前面的部分。

Python 代码示例

import re

def remove_last_simple_parentheses(input_str):
    # 正则解释:
    # (.*) 贪婪匹配到最后一个'('之前的所有内容(作为捕获组1)
    # \(.*\) 匹配最后一组()及其内部的所有内容
    return re.sub(r'(.*)\(.*\)', r'\1', input_str)

# 测试用例
test_case1 = "Hello (world) this is (a test) example"
test_case2 = "Only (one pair) here"
test_case3 = "No parentheses at all"

print(remove_last_simple_parentheses(test_case1))  # 输出: Hello (world) this is  example
print(remove_last_simple_parentheses(test_case2))  # 输出: Only  here
print(remove_last_simple_parentheses(test_case3))  # 输出: No parentheses at all

二、包含嵌套括号的场景(括号内还有其他())

如果你的字符串里存在嵌套括号(比如abc(def(ghi)jkl)mno(pqr)),上面的正则就会失效(因为贪婪匹配会从第一个(一直匹配到最后一个))。这时候我们需要用字符串遍历的方式,精准找到最后一组匹配的括号对:

Python 代码示例

def remove_last_nested_parentheses(input_str):
    # 先找到最后一个'('的位置
    last_open_idx = input_str.rfind('(')
    if last_open_idx == -1:
        return input_str  # 没有括号直接返回原字符串
    
    # 从最后一个'('开始,计数括号匹配,找到对应的')'
    bracket_count = 1
    for current_idx in range(last_open_idx + 1, len(input_str)):
        if input_str[current_idx] == '(':
            bracket_count += 1
        elif input_str[current_idx] == ')':
            bracket_count -= 1
            if bracket_count == 0:
                # 找到匹配的')',拼接前后部分返回
                return input_str[:last_open_idx] + input_str[current_idx+1:]
    
    # 如果最后一个'('没有对应的')',返回原字符串
    return input_str

# 测试用例
test_case4 = "abc(def(ghi)jkl)mno(pqr)"
test_case5 = "a(b(c)d(e))f"

print(remove_last_nested_parentheses(test_case4))  # 输出: abc(def(ghi)jkl)mno
print(remove_last_nested_parentheses(test_case5))  # 输出: a(b(c)d)f

这两种方案可以覆盖绝大多数场景,你可以根据自己的实际需求选择使用~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:15:56