Reputation: 1847
Give an string like '/apps/platform/app/app_name/etc'
, I can use
p = re.compile('/apps/(?P<p1>.*)/app/(?P<p2>.*)/')
to get two matched groups of platform
and app_name
, but how can I use re.sub
function (or maybe better way) to replace those two groups with other string like windows
and facebook
? So the final string would like /apps/windows/app/facebook/etc
.
Upvotes: 0
Views: 126
Reputation: 174696
Separate group replacement wouldn't be possible through regex. So i suggest you to do like this.
(?<=/apps/)(?P<p1>.*)(/app/)(?P<p2>.*)/
Then replace the matched characters with windows\2facebook/
. And also i suggest you to define your regex as raw string. Lookbehind is used inorder to avoid extra capturing group.
>>> s = '/apps/platform/app/app_name/etc'
>>> re.sub(r'(?<=/apps/)(?P<p1>.*)(/app/)(?P<p2>.*)/', r'windows\2facebook/', s)
'/apps/windows/app/facebook/etc'
Upvotes: 3