首页 > 解决方案 > Python Regex 检查字符串 1 和字符串 2 是否具有相同的模式

问题描述

我有 3 个字符串,例如:

s1 = 现在的时间是 10 点

s2 = 现在的时间是 {data} 0'clock

s3 = 现在的时间是 {data1} {data2}。

我如何得出结论 s1 和 s2 属于同一类型,而 s1 和 s3 属于不同类型。这里的 {data} 不限于数字。它也可能是字符串。有没有办法使用正则表达式或任何其他更简单的解决方案来做到这一点?

标签: pythonregexstring

解决方案


将您的{xxx}占位符转换.+?为将您的模板化字符串 ( s2and s3) 转换为正则表达式,然后查看它们是否与没有占位符 ( s1) 的字符串匹配。

import re

for template in (s2, s3):
    # convert templated string to regex
    template_as_re = re.sub(r'\{[^}]+\}', r'.+?', template)

    # try matching with test string
    if re.match(template_as_re, s1):
        print("{!r} is a match".format(template))

推荐阅读