我有一个其他人可以更改的字符串格式(只需说)
sample = f"This is a {pet} it has {number} legs"
我现在有两个字符串
a = "This is a dog it has 4 legs"
b = "This was a dog"
如何判断哪个字符串符合此sample
格式?
我有一个其他人可以更改的字符串格式(只需说)
sample = f"This is a {pet} it has {number} legs"
我现在有两个字符串
a = "This is a dog it has 4 legs"
b = "This was a dog"
如何判断哪个字符串符合此sample
格式?
我喜欢这些方法,但我找到了一个两行解决方案:
def pattern_match(input, pattern):
regex = re.sub(r'{[^{]*}','(.*)', "^" + pattern + "$")
if re.match(regex, input):
print(f"'{input}' matches the pattern '{pattern}'")
pattern_match(a, sample)
pattern_match(b, sample)
输出
'This is a dog it has 4 legs' matches the pattern 'This is a {pet} it has {number} legs'