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

Python正则表达式:用动态递增字符串替换首尾括号

Solution to Replace Parenthesized Substrings with Incremental Numbered Tags

Great question! This is a perfect use case for regular expressions combined with a stateful replacement function—here's exactly how you can achieve the desired output:

Step 1: Regex Pattern

We'll use the pattern \((.*?)\) to target each parenthesized substring:

  • \( matches the opening parenthesis (escaped because ( is a special regex character)
  • (.*?) is a non-greedy capture group that grabs the content inside the parentheses (non-greedy ensures we stop at the first closing parenthesis, avoiding accidental multi-match issues)
  • \) matches the closing parenthesis (also escaped)

Step 2: Incremental Replacement Logic

We need a counter that starts at 1 and increments for each match. For every parenthesized substring we find, we'll replace it with sb{N}-{content}-eb{N} where N is the current counter value.

Code Examples

Here are implementations in two popular languages:

JavaScript

const originalStr = "We want to visit that place (HBD) and meet our friends (DTO) after a long time. We really love having such gatherings at this time of year (XYZ). Let's do it.";
let counter = 1;

const modifiedStr = originalStr.replace(/\((.*?)\)/g, (match, capturedContent) => {
  return `sb${counter}-${capturedContent}-eb${counter++}`;
});

console.log(modifiedStr);

Python

import re

original_str = "We want to visit that place (HBD) and meet our friends (DTO) after a long time. We really love having such gatherings at this time of year (XYZ). Let's do it."
count = [1]  # Using a mutable list to track state in the callback

def replace_parentheses(match):
    content = match.group(1)
    result = f"sb{count[0]}-{content}-eb{count[0]}"
    count[0] += 1
    return result

modified_str = re.sub(r'\((.*?)\)', replace_parentheses, original_str)
print(modified_str)

Key Notes

  • The non-greedy .*? is crucial here—it ensures we don't accidentally match from the first opening parenthesis to the last closing parenthesis in the string (which would happen with the greedy .*).
  • This solution assumes your input has no nested parentheses. If you need to handle nested cases, you'd need a more complex regex (or a parser), but based on your example, this simple approach works perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:32:41