python - re.escape 的正则表达式匹配问题
问题描述
我想知道我的正则表达式有什么问题,以便我可以更正和匹配我的字符串。我使用的是 python 3.7
import re
a = '/hi/ji/hello/hello.log'
regex = rf".*\s+([\d]{4}-[\d]{2}-[\d]{2}\s+[\d]{2}:[\d]{2})\s+{re.escape(a)}"
line = r'-rw-rw---- hacluster haclient 6889422 2021-07-22 17:53 /hi/ji/hello/hello.log'
y = re.fullmatch(regex, line)
if y:
print(y.group(1))
解决方案
{2}
在 f-string 中被替换为 just 2
。您需要将它们加倍{}
以使它们字面化。
regex = rf".*\s+(\d{{4}}-\d{{2}}-\d{{2}}\s+\d{{2}}:\d{{2}})\s+{re.escape(a)}"
为了调试这个,我做了print(regex)
并注意到所有丢失的{}
.
推荐阅读
- tree - 删除树中的一个节点,使得森林中剩余的树都不包含超过一半的节点
- reactjs - React Props 没有带有浏览器转发按钮的最新 Redux 存储数据
- php - 从 WooCommerce 产品中获取所有产品类别名称
- javascript - 使用 SSMS 数据库的 Google Maps API
- angular - Firebase 5.8^ 发送电子邮件验证
- rust - 使用 impl Trait 时如何获得 Deref 强制(取 2)
- javascript - 使用 chart.js 在 javascript 中重新创建动画图
- java - 使用 ScrollView 发生自动滚动,并且没有通过 RelativeLayout.LayoutParams 获得边距底部
- python-3.x - print("Total number of sentence:", len(alice.split("."))) 怎么不正确?
- python - 在python中加入数据excel数据的循环文件名?