首页 > 解决方案 > 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))

标签: pythonpython-3.x

解决方案


{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)并注意到所有丢失的{}.


推荐阅读