如何用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
- 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)
- 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.
- For each match found, we take the captured content (
Why This Works
- It strictly isolates the content inside
{}so only hyphens in those sections are replaced—your outerpet-store-accountstays 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.jsonfiles.
内容的提问来源于stack exchange,提问作者RaamEE
相关产品推荐
相关产品推荐

