'How to check if there is a valid substitution value for string?

Given a string and a string template, how do I check if there is a valid variable that can be used as substitute?

For example,

def find_substitute(template: str, s: str) -> str:
    ...

template = "a_%(var)s_b_%(var)s_c"

find_substitute(template, "a_foo_b_foo_c")  # Should return foo
find_substitute(template, "a_foo_b_bar_c")  # Should raise, no valid substitution value
find_substitute(template, "a_foo_a_foo_a")  # Should raise, no valid substitution value

I could do template.split("%(var)s") and then try to match each section of the string, but I'm guessing there's a better way to do this, perhaps using regex.



Solution 1:[1]

You can use re.match for this.

import re

def find_substitute(template ,string):
    m = re.match(template, string)
    print(m.group(1)) if m else print("no match")

if __name__=="__main__":
    var = "foo"
    t = fr'a_({var})_b_(\1)_c'
    lines = ['a_foo_b_foo_c', 'a_bar_b_bar_c', 'a_foot_b_balls_c']
    for line in lines:
        find_substitute(t, line)

#output:
#foo
#no match
#no match

re.match returns a match object. You can use match object to get the full match or even the captured groups.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1