【问题标题】:re.IGNORECASE unexpected behaviour in python 2.7re.IGNORECASE python 2.7中的意外行为
【发布时间】:2016-02-09 05:39:04
【问题描述】:

将 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-zA-Z0-9 ]', '~', 'this (is) some tandom. text+ and [some] symbols {+/\-}')
>>> 'this ~is~ some tandom~ text~ and ~some~ symbols ~~~~~~'

我对 re.IGNORECASE 有什么遗漏吗?它不只匹配大写和小写字母,而其余部分(数字、特殊字符等)保持不变吗? (如果这可能有任何帮助,我正在使用 Anaconda 的 python 2.7)

【问题讨论】:

    标签: regex python-2.7


    【解决方案1】:

    你放错了标志值,使用

    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)
    

    IDEONE demo

    re.sub docs:

    re.sub(pattern, repl, string, count=0, flags=0) 可选参数count 是要替换的模式出现的最大数量; count 必须是非负整数。

    您使用 flag 而不是 count。当您传递re.IGNORECASE 时,count 变为非负数,并且只替换了一些字符,而不是所有字符。

    【讨论】:

    • 我想总是在参数之前明确指定“计数”和“标志”是一个好习惯。这将有助于防止此类问题
    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2017-03-05
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多