Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex with variable {}-multiplier [duplicate]

Tags:

python

regex

Say you wanted to create a pattern that matches sequences of var consecutive digits. You could do it this way:

p = re.compile(r"\d{"+str(var)+"}")

or this way:

p = re.compile(r"\d{%d}" % var)

But how would you do it using format()?

I tried both:

p = re.compile(r"\d{0}".format(var))

and:

p = re.compile(r"\d{{0}}".format(var))

but none of these worked.

like image 290
Marco Avatar asked Feb 16 '26 16:02

Marco


1 Answers

You need to actually have triple { and } - two for the escaped literal braces and one for the placeholder:

In [1]: var = 6

In [2]: r"\d{{{0}}}".format(var)
Out[2]: '\\d{6}'
like image 82
alecxe Avatar answered Feb 19 '26 06:02

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!