Python断言中如何忽略f-string指定片段,实现多值匹配?
在Python assert中用正则实现部分内容的多值匹配
当然可以用正则表达式实现这种需求,直接通过re.fullmatch()来验证目标字符串是否符合指定格式即可,具体写法如下:
示例代码
import re # 原固定值断言 # assert results.to_dict()["comment"] == "Retrying in 3600 seconds (1/5)" # 改为正则匹配,允许括号内第一个数字为1-5 assert re.fullmatch(r"Retrying in 3600 seconds \([1-5]/5\)", results.to_dict()["comment"]) is not None
正则表达式说明
\(和\):转义正则中的特殊字符(和),确保匹配字符串里的实际括号[1-5]:匹配1到5之间的任意单个数字- 其余部分和原固定字符串完全一致,保证除了指定位置外的内容严格匹配
补充说明
如果需要更灵活的匹配(比如3600秒也可能是变量),可以调整正则中的对应部分,比如用\d+匹配任意数字:
assert re.fullmatch(r"Retrying in \d+ seconds \([1-5]/5\)", results.to_dict()["comment"]) is not None
内容的提问来源于stack exchange,提问作者lukos06
相关产品推荐
相关产品推荐

