如何检查字符串是否有有效的替换值?

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

给定一个字符串和一个字符串模板,如何检查是否存在可用作替代的有效变量?

例如,

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

我可以 template.split("%(var)s") 然后尝试匹配字符串的每个部分,但我猜有更好的方法可以做到这一点,也许使用正则表达式。

您可以为此使用 re.match

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_()_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. 您可以使用匹配对象来获得完整匹配甚至捕获的组。