Python Regex Partial Replace

August 9, 2017
Use capture group and reference: re.sub(r”(match)(replace)", r”\1new”, string)

Replacing only part of the matched string.

For the string I want to identify url and replace the subdomain only.

import re

url = ""
re.sub(r"(://)([^.]+)(\.mydomain\.com)", r"\1www\3", url)
# Output
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.