Python - re.error: unterminated character set at position

ⅰ亾dé卋堺 提交于 2019-12-01 15:31:29

问题


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 it's, most likely, because of the metacharacters "{}, [], ()". Is there any regular expression that can make finditer ignore it?


回答1:


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.



来源:https://stackoverflow.com/questions/54135606/python-re-error-unterminated-character-set-at-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!