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

如何用Python正则替换URL中花括号内的短横线为下划线

Solution to Replace Hyphens with Underscores Only Inside Curly Braces in URLs

Got it, here's a clean, efficient way to handle this using Python's re module—perfect for your Swagger URL parsing use case:

Step-by-Step Explanation

We need to target only the text inside curly braces ({...}) and replace hyphens there with underscores, leaving hyphens outside untouched. The key is to use a regex that captures the content inside braces, then apply the replacement just to that captured group.

Code Implementation

import re

# Example URL extracted from your Swagger api.json
swagger_url = "https://api.example.com/pet-store-account/{pet-owner}/orders/{order-id}/details/{shipping-method}"

# Perform the targeted replacement
processed_url = re.sub(
    r'\{([^}]+)\}',
    lambda match: '{' + match.group(1).replace('-', '_') + '}',
    swagger_url
)

print(processed_url)
# Output: https://api.example.com/pet-store-account/{pet_owner}/orders/{order_id}/details/{shipping_method}

Breakdown of the Regex & Logic

  1. Regex Pattern: \{([^}]+)\}
    • \{ matches the opening curly brace (escaped because { is a special regex character)
    • ([^}]+) captures all characters except the closing brace—this is inherently non-greedy, as it stops at the first } it encounters, so it won't accidentally span multiple brace pairs
    • \} matches the closing curly brace (also escaped)
  2. Replacement Lambda:
    • For each match found, we take the captured content (match.group(1)—the stuff inside the braces), replace all hyphens with underscores, then wrap it back in curly braces to maintain the parameter format.

Why This Works

  • It strictly isolates the content inside {} so only hyphens in those sections are replaced—your outer pet-store-account stays exactly as is.
  • The pattern handles multiple path parameters seamlessly, which is common in Swagger specs.
  • It’s lightweight and doesn’t require complex parsing, making it ideal for processing URLs from Swagger api.json files.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:38:50