python regex transpose capture group into another regex

Question:

I have:

regex1 = 'CCbl([a-z]{2})la-12([0-9])4'
inputstring = 'CCblabla-1234'
regex2_to_get_substituted = 'fof([a-z]{2})in(.)ha'

desired output = 'fofabin3ha'

Basically I want to get result of the capture groups from regex1 and transpose them into the same positions of nth capture groups in regex2 as a substitution.

Asked By: tooptoop4

||

Answers:

If I understand you correctly, you just need a template for your desired output:

import re

regex1 = r"CCbl([a-z]{2})la-12([0-9])4"
string = "CCblabla-1234"
template = "fof{}in{}ha"

groups = re.search(regex1, string).groups()
print(template.format(*groups))   # fofabin3ha

Those {}s in template will be substituted with the values of the .groups().


After discussion in comments:

import re

regex1 = r"CCbl([a-z]{2})la-12([0-9])4"
regex2 = r"fof([a-z]{2})in(.)ha"
string = "CCblabla-1234"

groups = re.search(regex1, string).groups()
print(re.sub(r"(.*?)", "{}", regex2).format(*groups))  # fofabin3ha

This converts the regex2 groups into {} so that you can fill them later with the .groups() of regex1.

Answered By: S.B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.