首页 > 解决方案 > re.error:读取搅拌时位置未终止的字符集

问题描述

这是我得到的字符串

这给了搅拌

Immunodeficiency with increased immunoglobulin [M] [IgM] Maternal care for anti-D [Rh] antibodies, unspecified trimester

我试图在 Python 中的字符串中查找多次出现的字符串,并获取它们的索引。

所以,使用输入字符串

  char = random input string

我想要这样的结果:

result = [[index, index, index],[index, index, index ]]

所以,这是我使用的代码。

            a = [m.start() for m in re.finditer(char,given string)]

,但它不适用于元字符,并导致 re.error: unterminated character set at position 0

如何改进此代码?

标签: pythonlisterror-handlingre

解决方案


如果要re.finditer()与随机输入字符串一起使用,则需要对其进行转义,以防它包含在正则表达式中具有特殊含义的字符。

regex = re.escape(char)
a = [m.start() for m in re.finditer(regex,given string)]

推荐阅读