0

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!

1
  • You would be interested in named capturing groups: see this partially complete regex _(?P<element>[^_]+)\.(?P<frame>\d+)\.exr$, put forth some more effort, and come back if you get stuck. Commented Mar 10, 2020 at 17:01

2 Answers 2

2

I would go for named capturing groups and extract the desired results with the groupdict() function:

import re

file_path = "/101-001-015_fg01/4312x2156/101-001-015_fg01.0001.exr"
rx = r"\/(?P<CODE>.+)_(?P<ELEMENT>.+)\/(?P<WIDTH>.+)x(?P<HEIGHT>.+)\/.+\.(?P<FRAME>\w+).exr"
m = re.match(rx, file_path)

result = m.groupdict()
# {'CODE': '101-001-015', 'ELEMENT': 'fg01', 'WIDTH': '4312', 'HEIGHT': '2156', 'FRAME': '0001'}

Sign up to request clarification or add additional context in comments.

Comments

1

Kind of similar like Simon did, I'll also try with named captured group

import re
regex = r"(?P<CODE>[0-9-]+)_(?P<ELEMENT>[0-9a-z]+)\/(?P<WIDTH>[0-9]+)x(?P<HEIGHT>[0-9]+)\/\1_\2\.(?P<FRAME>[0-9]+)\.exr"
test_str = "101-001-015_fg01/4312x2156/101-001-015_fg01.0001.exr"
matches = re.match(regex, test_str)
print(matches.groupdict())

DEMO: https://rextester.com/BEZH21139

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.