Regex python 2.7中的re.IGNORECASE意外行为

Regex python 2.7中的re.IGNORECASE意外行为,regex,python-2.7,Regex,Python 2.7,将re.IGNORECASE添加到我的正则表达式会导致某些匹配失败。这就是我所尝试的: print re.sub(r'[^a-z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}', re.IGNORECASE) >>>'this ~is~ some tandom. text+ and [some] symbols {+/\\-}' 我们可以看到,上面的许多符号没有被替换为“~”,但是当我尝

将re.IGNORECASE添加到我的正则表达式会导致某些匹配失败。这就是我所尝试的:

print re.sub(r'[^a-z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}', re.IGNORECASE)
>>>'this ~is~ some tandom. text+ and [some] symbols {+/\\-}'
我们可以看到,上面的许多符号没有被替换为“~”,但是当我尝试同样的方法而不重新命名时,所有的特殊字符都被替换为“~”

print re.sub(r'[^a-zA-Z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}')
>>> 'this ~is~ some tandom~ text~ and ~some~ symbols ~~~~~~'
关于re.IGNORECASE我有什么遗漏吗?它不是只匹配大写字母和小写字母,而保持其余字母(数字、特殊字符等)不变吗?
(我正在使用Anaconda的Python2.7,如果这可能有帮助的话)

如果您将标志值放错了位置,请使用

print re.sub(r'[^a-z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}', flags=re.IGNORECASE)
# or
print re.sub(r'[^a-z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}', 0, re.IGNORECASE)

见:

re.sub(模式、应答、字符串、计数=0、标志=0)
可选参数
count
是要替换的最大模式出现次数<代码>计数必须是非负整数


使用标志而不是计数。当您传递
re.IGNORECASE
时,
count
变为非负数,只替换了部分字符,而不是全部字符。

我想最好总是在参数之前明确指定“count”和“flags”。。这将有助于防止此类问题