简体   繁体   中英

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 (eg foofoofoo) within a string (eg "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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM