python - 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
如何改进此代码?
解决方案
如果要re.finditer()
与随机输入字符串一起使用,则需要对其进行转义,以防它包含在正则表达式中具有特殊含义的字符。
regex = re.escape(char)
a = [m.start() for m in re.finditer(regex,given string)]
推荐阅读
- php - 始终在 WooCommerce 电子邮件通知中显示送货地址
- django - 'NoneType' 类型的参数对于 django 字符串“”是不可迭代的
- ios - 如何从 UI 选择器视图重新加载数据并使用转换关闭选择器视图
- c - 计算具有相同连续元素的块的元素数
- python-2.7 - 删除句号前的字符
- python - 在 Pytorch 中逐元素应用 Kullback-Leibler(又名 kl 散度)
- sql - 如何在 SSMS 2008 中执行 IF EXISTS UPDATE ELSE INSERT 语法
- javascript - 简化 semver 版本比较逻辑
- python - 如何在不换行的情况下打印完整的 NumPy 数组(在 Jupyter Notebook 中)
- docker - kata 容器可以用作沙箱来运行不受信任的代码吗?