In Python, I'm looking for a way to extract regex groups given a string and a matching template pattern, for example:
file_path = "/101-001-015_fg01/4312x2156/101-001-015_fg01.0001.exr"
file_template = "/{CODE}_{ELEMENT}/{WIDTH}x{HEIGHT}/{CODE}_{ELEMENT}.{FRAME}.exr"
The output I'm looking for is the following:
{
"CODE": "101-001-015",
"ELEMENT": "fg01",
"WIDTH": "4312",
"HEIGHT: "2156",
"FRAME": "0001"
}
My initial approach was to format my template and find any and all matches, but it's not ideal:
import re
re_format = file_template.format(SHOT='(.*)', ELEMENT='(.*)', WIDTH='(.*)', HEIGHT='(.*)', FRAME='(.*)')
search = re.compile(re_format)
result = search.findall(file_path)
# result: [('101-001-015', 'fg01', '4312', '2156', '101-001-015', 'fg01.000', '')]
All template keys could be contain various characters and be of various lengths so I'm looking for a good matching algorithm. Any ideas if and how this could be done with Python re or any alternative libraries?
Thanks!
_(?P<element>[^_]+)\.(?P<frame>\d+)\.exr$, put forth some more effort, and come back if you get stuck.