Python, getting ValueError: unexpected '{' in field name when using format variable in a string with regex
Question:
This code runs a query on the string exactly as is it should.
bInfoPList = re.findall('{searchString}'.format(searchString = searchString), content, re.M + re.S)
This code returns: "ValueError: unexpected ‘{‘ in field name"
bInfoPList = re.findall('{searchString}s*=s*{{[Pp]lainlist|.*'.format(searchString = searchString), content, re.M + re.S)
The format of the query strings and variable seems identical except for the second one being a longer and having some regex characters. Why doesn’t the second one work? What do I need to change?
Answers:
The mechanism for escaping curly braces is different to what you were trying.
Do this:
bInfoPList = re.findall(f'{searchString}s*=s*{{[Pp]lainlist|.*', content, re.M + re.S)
This code runs a query on the string exactly as is it should.
bInfoPList = re.findall('{searchString}'.format(searchString = searchString), content, re.M + re.S)
This code returns: "ValueError: unexpected ‘{‘ in field name"
bInfoPList = re.findall('{searchString}s*=s*{{[Pp]lainlist|.*'.format(searchString = searchString), content, re.M + re.S)
The format of the query strings and variable seems identical except for the second one being a longer and having some regex characters. Why doesn’t the second one work? What do I need to change?
The mechanism for escaping curly braces is different to what you were trying.
Do this:
bInfoPList = re.findall(f'{searchString}s*=s*{{[Pp]lainlist|.*', content, re.M + re.S)