0

Take the following code:

import re

def test_targeting_file_matching():
    a = "177"
    b = "1"
    filenames = ["177__1.csv", "177__1__000000000000.csv"]

    targeting_file_pattern = re.compile(rf"{a}__{b}(__\d{12})?\.csv")

    for filename in filenames:
        if targeting_file_pattern.match(filename):
            print(f"Matched: {filename}")
        else:
            print(f"Not Matched: {filename}")

test_targeting_file_matching()

It is supposed to match the two files, but only 177__1.csv is matched. I can't see the problem with my regex expression

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • 1
    @bobblebubble This is a *string* related problem, not a regex. – Wiktor Stribiżew Aug 30 '23 at 09:10
  • **Oy, enough with the rollback war.** There are good justifications both ways about these tags, but if you keep doing that, neither of you will have the chance to make that decision. – E_net4 Aug 30 '23 at 09:18
  • 4
    I agree with bobble. Although the root cause is not about the regex syntax, but this mistake occurs while using regex in python, since regex and f-string both have special meanings for `{}`. It helps other people with the same issue identify the problem. – Hao Wu Aug 30 '23 at 09:25

1 Answers1

2

You're using an f-string. {12} doesn't mean "match 12 of the previous thing". It gets string-formatted to 12, matching literal 1 and 2 characters.

You need to escape the braces: {{12}}

user2357112
  • 260,549
  • 28
  • 431
  • 505