You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Python正则表达式移除文本中[]及()内的内容?

Hey there! Let's get this sorted out for you. Your goal is to strip out all content inside curly braces {}, square brackets [], and parentheses () (including nested ones) to end up with just abc—and your current code is missing a couple key pieces.

First, let's break down what's not working in your original code:

  • You manually removed curly braces, but didn't handle square brackets at all.
  • While your regex \(.*\) works for your specific example (since it greedily matches from the first ( to the last )), it would fail if you had multiple non-nested parentheses (like abc (x) y (z)—it would erase everything from the first ( to the last )).

Here's a robust solution that handles all three bracket types, including nested parentheses, in one go:

import re

with open('data.txt') as f:
    input_text = f.read()  # Avoid using `input` as a variable name—it's a Python built-in!

# Regex pattern to match curly braces, square brackets, and balanced parentheses (with nesting)
bracket_pattern = r'\{[^}]*\}|\[(?:[^\[\]]|(?R))*\]|\((?:[^()]|(?R))*\)'

# Replace all matched bracket content with empty string, then clean up extra spaces
output = re.sub(bracket_pattern, "", input_text).strip()

print(output)

Let me explain what this does:

  • The regex uses three branches separated by |:
    1. \{[^}]*\}: Matches curly braces and their content (no nesting needed here, so we just match everything up to the closing }).
    2. \[(?:[^\[\]]|(?R))*\]: Matches balanced square brackets (handles nested brackets if they ever show up).
    3. \((?:[^()]|(?R))*\): Matches balanced parentheses—this is the key fix for nested cases like (b(c)d).
  • After replacing all bracket content, strip() removes any leading/trailing whitespace left behind, leaving you with clean abc.

Testing this with your input {[a] abc (b(c)d)} will give you exactly the expected output: abc.

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

火山引擎 最新活动