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

如何删除字符串中括号及括号内部的内容?

How to Remove Parentheses and Their Contents from a String

If you need to strip out all parentheses (and everything inside them) from your string, regular expressions are the most straightforward approach across most programming languages. Here are solutions for a few common ones:

Python

Use the re module's sub function to replace any matching parentheses and their contents with an empty string:

import re

samplevalue = "1. e40 e51 2. f31 f56 (f16) 3. j40 h51 4. k31 (c18) k56 "
cleaned_value = re.sub(r'\([^)]*\)', '', samplevalue)
print(cleaned_value)  # Output: "1. e40 e51 2. f31 f56  3. j40 h51 4. k31  k56 "

Note: This leaves a double space where the parentheses were. If you want to collapse multiple spaces into one, add an extra step with re.sub(r'\s+', ' ', cleaned_value).

JavaScript

Use the String.replace() method with a regex that includes the global (g) flag to replace all occurrences:

let samplevalue = "1. e40 e51 2. f31 f56 (f16) 3. j40 h51 4. k31 (c18) k56 ";
let cleanedValue = samplevalue.replace(/\([^)]*\)/g, '');
console.log(cleanedValue); // Output: "1. e40 e51 2. f31 f56  3. j40 h51 4. k31  k56 "

Again, to fix double spaces, you can chain another replace: .replace(/\s+/g, ' ')

C#

Use Regex.Replace from the System.Text.RegularExpressions namespace:

using System.Text.RegularExpressions;

string samplevalue = "1. e40 e51 2. f31 f56 (f16) 3. j40 h51 4. k31 (c18) k56 ";
string cleanedValue = Regex.Replace(samplevalue, @"\([^)]*\)", "");
Console.WriteLine(cleanedValue); // Output: "1. e40 e51 2. f31 f56  3. j40 h51 4. k31  k56 "

To clean up extra spaces, use Regex.Replace(cleanedValue, @"\s+", " ")

Regex Explanation

The pattern \([^)]*\) works like this:

  • \(: Matches the opening parenthesis (escaped because ( is a special regex character)
  • [^)]*: Matches any character except a closing parenthesis ([^)]), zero or more times (*)
  • \): Matches the closing parenthesis (escaped as well)

This ensures we only remove content inside matching parentheses. Note that this doesn’t handle nested parentheses (like (a(b)c)), but your example doesn’t have that scenario.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:44:03