简体   繁体   English

Python:动态匹配正则表达式

[英]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").我想在字符串(例如“barbarfoofoofoobarbarbar”)中搜索连续重复的 substring(例如 foofoofoo)。 However, I need both the repeating substring (foo) and the number of repetitions (In this case, 3) to be dynamic, contained within variables.但是,我需要重复的 substring (foo) 和重复次数(在本例中为 3)都是动态的,包含在变量中。 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.由于重复的正则表达式是 re{n},这些花括号与我放在字符串中的变量冲突,因为它们也需要花括号。

The code should match foofoofoo, but NOT foo or foofoo.代码应该匹配 foofoofoo,但不匹配 foo 或 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或 escaping 与

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?也许我可以使用 findall 或 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}" .对于字符串barbarfoofoofoobarbarbar ,如果您想捕获foofoofoo ,则正则表达式将为r"(foo){3}" if you wanted to do this dynamically, you could do fr"({your_string}){{{your_number}}}" .如果您想动态执行此操作,可以执行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 } .如果您想在 f 字符串中使用花括号,请使用{{}} ,它将按字面意思打印为{}

Also, str is not a good variable name because str is a class (the string class).此外, str不是一个好的变量名,因为str是 class(字符串类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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