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

如何将字符串中方括号[]包裹的内容删除并替换为空

移除字符串中[]包裹内容的实现方案

核心实现思路

使用非贪婪模式的正则表达式匹配所有被方括号包裹的内容,再替换为空字符串即可。匹配规则为\[.*?\]:

  • \[ 匹配左方括号
  • .*? 非贪婪匹配任意字符,避免多个方括号存在时错误匹配跨括号的内容
  • \] 匹配右方括号

替换完成后可根据需求选择是否处理生成的多余连续空格。

常用编程语言实现示例

Python 实现

import re

original_str = "The code is [cid:7108371312034834373] used to create your new account."
# 替换方括号内容
result_str = re.sub(r'\[.*?\]', '', original_str)
# 可选:将多个连续空格替换为单个空格并去除首尾空格
result_str = re.sub(r'\s+', ' ', result_str).strip()
print(result_str) 
# 输出:The code is used to create your new account.

JavaScript 实现

const originalStr = "The code is [cid:7108371312034834373] used to create your new account."
const resultStr = originalStr.replace(/\[.*?\]/g, '').replace(/\s+/g, ' ').trim()
console.log(resultStr)
// 输出:The code is used to create your new account.

Java 实现

import java.util.regex.Pattern;

public class RemoveBracketContent {
    public static void main(String[] args) {
        String originalStr = "The code is [cid:7108371312034834373] used to create your new account.";
        String resultStr = originalStr.replaceAll("\\[.*?\\]", "").replaceAll("\\s+", " ").trim();
        System.out.println(resultStr);
        // 输出:The code is used to create your new account.
    }
}

特殊场景说明

如果你的使用场景存在方括号嵌套的情况(如a[b[c]d]e),上述正则仅能匹配到第一层右括号,需要根据对应语言调整正则逻辑或者使用栈结构遍历处理,单层方括号场景下上述方案可直接使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:54:04