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

如何用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 either Filialy or MN.
  • 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>':

  1. We replace the first capture group with <address>
  2. Insert the preserved middle content (from the second group, referenced as \2)
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:45:02