如何用Python正则按条件替换指定格式子串为<address>标签?
Solution for Targeted Regex Replacement in Python
Got it, let's work through this cleanly. You want to tweak specific bracketed substrings: swap their prefix (matching \[[\d\.]+_(?:Filialy|MN)) with <address>, replace the closing ] with </address>, and keep the middle content intact. Here's how to do it efficiently with Python's re module:
import re # Example input string input_text = "Check this [2.7_Filialy_MainStreet] and that [5_MN_WestEnd] too" # Regex pattern with capture groups to isolate parts we need pattern = r'(\[[\d\.]+_(?:Filialy|MN))([^\]]+)(\])' # Perform the single-pass replacement output_text = re.sub(pattern, r'<address>\2</address>', input_text) print(output_text) # Output: "Check this <address>_MainStreet</address> and that <address>_WestEnd</address> too"
Breakdown of how this works:
Let's unpack the regex and replacement logic:
- First capture group
(\[[\d\.]+_(?:Filialy|MN)): This targets exactly the prefix you want to replace—including the opening[, digits/decimal points, underscore, and eitherFilialyorMN. - Second capture group
([^\]]+): This grabs all content between the prefix and closing]—this is the part we want to preserve inside the<address>tags. - Third capture group
(\]): This matches the closing]that we'll swap for</address>.
In the replacement string r'<address>\2</address>':
- We replace the first capture group with
<address> - Insert the preserved middle content (from the second group, referenced as
\2) - Replace the third capture group with
</address>
This method handles the entire modification in one pass, ensuring we only target the exact substrings you specified.
内容的提问来源于stack exchange,提问作者Petr Petrov
相关产品推荐
相关产品推荐

