« Back to Index

[Python regex replace with capture group]

View original Gist on GitHub

Tags: #python #regex #replace #substring

Python regex replace with capture group.py

html = '<iframe src="http://www.foo.com/?video_id=1234" allowfullscreen>'

re.sub('src="([^"]+)', lambda o: 'src="{}&platform=mobile_app'.format(o.groups(0)[0]), html)
# '<iframe src="http://www.foo.com/?video_id=1234&platform=mobile_app" allowfullscreen>'

# Alternative that uses f string formatting
re.sub('src="([^"]+)', lambda o: f'src="{o.groups(0)[0]}&platform=mobile_app', html)