Python: Dynamic matching with regular expressions

I've been trying several things to use variables inside a regular expression. None seem to be capable of doing what I need.

I want to search for a consecutively repeated substring (e.g. foofoofoo) within a string (e.g. "barbarfoofoofoobarbarbar"). However, I need both the repeating substring (foo) and the number of repetitions (In this case, 3) to be dynamic, contained within variables. Since the regular expression for repeating is re{n}, those curly braces conflict with the variables I put inside the string, since they also need curly braces around.

The code should match foofoofoo, but NOT foo or foofoo.

I suspect I need to use string interpolation of some sort.

I tried stuff like

n = 3
str = "foo"
string = "barbarfoofoofoobarbarbar"
match = re.match(fr"{str}{n}", string)

or

match = re.match(fr"{str}{{n}}", string)

or escaping with

match = re.match(fr"re.escape({str}){n}", string)

but none of that seems to work. Any thoughts? It's really important both pieces of information are dynamic, and it matches only consecutive stuff. Perhaps I could use findall or finditer? No idea how to proceed.

Something I havent tried at all is not using regular expressions, but something like

if (str*n) in string:
    match

I don't know if that would work, but if I ever need the extra functionality of regex, I'd like to be able to use it.

Upvotes: 2

Views: 2651

Answers (1)

Gaultier Gotz
Gaultier Gotz

Reputation: 46

For the string barbarfoofoofoobarbarbar, if you wanted to capture foofoofoo, the regex would be r"(foo){3}". if you wanted to do this dynamically, you could do fr"({your_string}){{{your_number}}}".

If you want a curly brace in an f-string, you use {{ or }} and it'll be printed literally as { or }.

Also, str is not a good variable name because str is a class (the string class).

Upvotes: 3

Related Questions