Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - re.error: unterminated character set at position

Tags:

python

The following code:

text = "I'm a string that contains this characters {}, [], ()"
slice = "this characters {}, [], ()"
print([ (m.start(0), m.end(0)) for m in re.finditer(slice, text) ])

Shows the error:

re.error: unterminated character set at position 12

That is, most likely, because of the metacharacters "{}, [], ()". Is there any regular expression that can make finditer ignore it?

like image 700
arksdf Avatar asked Jan 10 '19 19:01

arksdf


1 Answers

You must escape the special characters in your regex:

slice = "this characters \{}, \[], \(\)"

Note that only the opening brace and square bracket need an escape, but both parentheses.

like image 189
DYZ Avatar answered Nov 20 '22 19:11

DYZ