0

I would like to substitute multiple regex groups in a string. However I would like that each group be substituted differently.

Given the string:

"{Family} is made up of [Father], [Mother], and [Daughter] also there are 100 monkeys in a tree."

I would like to obtain:

"<b>{Family}</b> is made up of <i>[Father]</i>, <i>[Mother]</i>, and <i>[Daughter]</i> also there are <h4>100</h4> monkeys in a tree."

I was using multiple re.sub passes. I'm very new to regex and couldn't find information as to whether it is possible with a single substitution? If so what does the substitution format look like?

This is what I have:

import re

text = re.sub(r'(\{[^\}]*\})', r'<b>\1</b>', text)
text = re.sub(r'(\[[^\]]*\])', r'<i>\1</i>', text)
re.sub(r'(\d+)', r'<h>\1</h>, text)

Is the following possible? Or even the proper approach?

re.sub(r'(\{[^\}]*\})|(\[[^\]]*\]|(\d+))', ???, text)

EDIT:

Changed the question to be more specific. Thanks for the solutions, but they don't necessarily allow for you to capture any regex group and don't specifically answer whether the substitute method allows for this directly.

Klaudikus
  • 382
  • 3
  • 12
  • http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. This might help. You can have a mapping `{"{":'"", "}": ""}` – pmuntima Feb 06 '17 at 16:08
  • https://gist.github.com/bgusach/a967e0587d6e01e889fd1d776c5f3729 . A cleaner piece of code based on the previous answer. – pmuntima Feb 06 '17 at 16:22

0 Answers0