0

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.

2
  • Are you sure you want to be using a regex and not os.path for this? Commented Dec 25, 2014 at 9:29
  • @NPE I have no idea about the relationship between string replace and os.path. but maybe you can show me some code:) Commented Dec 25, 2014 at 9:34

1 Answer 1

3

Separate group replacement wouldn't be possible through regex. So i suggest you to do like this.

(?<=/apps/)(?P<p1>.*)(/app/)(?P<p2>.*)/

DEMO

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.