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

如何移除字符串中除首尾实例外的所有[和]字符?

Got it, let's solve this! The goal is to keep only the very first [ and last ] in your string, and strip out all other square brackets in between. Here are two straightforward ways to do this:

Method 1: Simple String Manipulation (Easy to Read)

This approach breaks the string into parts, cleans the middle section, then reassembles everything. It’s perfect if you prefer code that’s easy to follow at a glance.

For example, in Python:

input_str = "[foo:[foo, foo2], bar:[bar]]"

# Check if the string starts and ends with brackets (adjust if your input might not follow this pattern)
if input_str.startswith('[') and input_str.endswith(']'):
    # Extract the middle part by removing the first and last characters
    middle_section = input_str[1:-1]
    # Remove all inner square brackets
    cleaned_middle = middle_section.replace('[', '').replace(']', '')
    # Reattach the outer brackets to get the final result
    output_str = '[' + cleaned_middle + ']'
else:
    # If there are no outer brackets, just remove all brackets entirely
    output_str = input_str.replace('[', '').replace(']', '')

print(output_str)  # Output: [foo:foo, foo2, bar:bar]

Method 2: Regular Expressions (Concise)

If you prefer regex, we can target only the inner brackets for removal. We’ll run two quick replacements: one to eliminate all [ except the first, and another to remove all ] except the last.

Again, in Python:

import re

input_str = "[foo:[foo, foo2], bar:[bar]]"

# Remove all '[' except the very first instance
step1 = re.sub(r'(?<!^\[)\[', '', input_str)
# Remove all ']' except the very last instance
output_str = re.sub(r'\](?!$)', '', step1)

print(output_str)  # Output: [foo:foo, foo2, bar:bar]

Let me break down the regex patterns for clarity:

  • (?<!^\[)\[: The (?<!...) is a negative lookbehind. It matches a [ only if it’s NOT immediately after the start of the string (so it skips the first [).
  • \](?!$): The (?!...) is a negative lookahead. It matches a ] only if it’s NOT immediately followed by the end of the string (so it skips the last ]).

Both methods will give you exactly the output you want. The string manipulation approach is great for readability, while regex is more compact for those comfortable with it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:05