python - Python Regex 检查字符串 1 和字符串 2 是否具有相同的模式
问题描述
我有 3 个字符串,例如:
s1 = 现在的时间是 10 点
s2 = 现在的时间是 {data} 0'clock
s3 = 现在的时间是 {data1} {data2}。
我如何得出结论 s1 和 s2 属于同一类型,而 s1 和 s3 属于不同类型。这里的 {data} 不限于数字。它也可能是字符串。有没有办法使用正则表达式或任何其他更简单的解决方案来做到这一点?
解决方案
将您的{xxx}
占位符转换.+?
为将您的模板化字符串 ( s2
and 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))
推荐阅读
- sql - 将类型作为参数传递给 Oracle 函数
- node.js - nodejs中线程的实现
- github - Tailoring blog and categories in Jekyll GitHub
- php - 我可以在准备好的语句中混合无界参数吗?
- wordpress - Ability to identify customers / orders placed via the REST API
- thymeleaf - 多个类追加和间距
- fabricjs - Fabricjs将多页PDF加载为多个画布
- c# - SQLite:添加 DateTime 和 TimeSpan
- c# - Google Drive ApI V3 Migration for Xamrin.Android
- html - 标签、输入和错误相互水平对齐的表单组