0

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Leonardus Chen
  • 1,103
  • 6
  • 20

1 Answers1

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.

anotherGatsby
  • 1,568
  • 10
  • 21
  • Hi, just a question... why you use `match` and not `search`? both return a `Match` object but with `re.match` consider the pattern at beginning of string only, right? – cards Apr 27 '22 at 08:47
  • @cards `match` is anchored at the beginning, which is suitable in this case. Also its faster than `search`. Read more about it here: https://stackoverflow.com/a/180993/7369809 – anotherGatsby Apr 27 '22 at 08:53
  • I missunderstood the original question, thanks for your reply:) – cards Apr 27 '22 at 08:58