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.

Example:
For the string http://subdomain.mydomain.com/hello.html I want to identify mydomain.com url and replace the subdomain only.

import re

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