Rocky
Rocky

Reputation: 57

Regex matching issue with re.escape

I would like to know what is wrong in my regex so that I can correct and match my string.I am using 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))

Upvotes: 0

Views: 65

Answers (1)

Barmar
Barmar

Reputation: 780899

{2} in an f-string is replaced with just 2. You need to double the {} to make them literal.

regex = rf".*\s+(\d{{4}}-\d{{2}}-\d{{2}}\s+\d{{2}}:\d{{2}})\s+{re.escape(a)}"

To debug this I did print(regex) and noticed all the missing {}.

Upvotes: 1

Related Questions