Home > Software engineering >  python regex transpose capture group into another regex
python regex transpose capture group into another regex

Time:12-20

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.

CodePudding user response:

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.

  • Related