Regular expressions and f-strings

I am trying to use f-strings to construct regular expressions. Unfortunately, regular expressions make heavy use of the { and } symbols and f-strings do not support escaping them with \.
An example is shown below:
re = rf'\{,2\}
I was hoping to see the string ‘{,2}’ in re but instead, I got this Python error:
SyntaxError: f-string expression part cannot include a backslash.
Is it possible to use f-strings like this, and if so, how?

When I construct regexes that need to include string variables (not literals only) the Old Gods work great: "%s" and %

E.g.

pattern = r'%s' % search_text

Remember to put more than one trailing arg in a tuple.

If you need a curly brace you need to double it: re = rf'{{,2}}'

2 Likes

Doubling the { and } works, thankyou.

For reference, see

The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace.