I’d like to do regexp searches based on a variable’s value.
In Py2.x this works very well:
pattern = re.compile(r"\b[a-zA-Z]{%(min_length)d,}\b" % locals())
When I try to port it to the new str.format() notation I get something like this:
pattern = re.compile(r"\b[a-zA-Z]{{0},}\b".format(min_length))
and this gives me an error as the braces from repetition get confused with the ones from str.format():
ValueError: Single '}' encountered in format string
I’m sure you can think of more examples like this where format() clashes with repetition.
What is the correct way to supply external value to regexp’s repetition through str.format()? % operator does not work in Py3.
Just use the old version –
%string formatting is still supported in Python 3.x, and it won’t go away. If you insist on using the new syntax, double the braces that are not indicating fields: