【问题标题】:Ignore special characters from a list excluding the mentioned characters忽略列表中的特殊字符,不包括提到的字符
【发布时间】:2019-08-11 22:32:21
【问题描述】:

我一直在使用正则表达式来忽略列表中的特殊字符。但是现在我想忽略除用户提到的一些特殊字符之外的特殊字符。

我目前用来删除特殊字符的代码是:

final_list=[re.sub('[^a-zA-Z0-9]+', '', _)for _ in a]

当我想删除列表中的所有特殊字符时,这很好用。

输入:

["on@3", "two#", "thre%e"]

输出:

['on3', 'two', 'three']

但是我的期望是如果我忽略除$#%以外的特殊字符

输入:

["on@3", "two#", "thre%e"]

输出:

['on3', 'two#', 'thre%e']

这是我的预期输出

$#% 只是一个例子。用户可以提及任何特殊字符,我需要代码不删除用户提到的特殊字符,而是删除所有其他特殊字符。

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    将这些字符添加到正则表达式中

    [re.sub('[^a-zA-Z0-9$#%]+', '', _)for _ in a]
                        ^^^

    正如@DYZ 提到的,你也可以使用 '[^\w$#%]+' 正则表达式

    [re.sub('[^\w$#%]+', '', _)for _ in a]
    

    更新-1

    import re
    a = ["on@3", "two#", "thre%e"]
    special_char_to_be_removed = "%" # here you can change the values
    regex = '[^\w{your_regex}]+'.format(your_regex=special_char_to_be_removed)
    [re.sub(regex, '', _)for _ in a]

    【讨论】:

    • 感谢您的回复。当 $#% 应该始终被忽略时,这很好用,但这会根据要求而变化,它可能是 ^&* 或 !@。用户将根据自己的要求更改要避免的特殊字符。
    【解决方案2】:

    只需将字符列表添加到列表中即可。

    import re
    
    a = ["on@3", "two$", "thre%e"]
    
    final_list = [re.sub('[^a-zA-Z0-9\$#%]+', '', _) for _ in a]
    
    print final_list
    

    输出

    ['on3', 'two$', 'thre%e']
    

    $ 在正则表达式中具有含义,因此您需要使用\ 对其进行转义

    如果你想接受用户输入,只需使用

    import re
    
    a = ["on@3", "two$", "thre%e"]
    
    except_special_chars = input('Exceptions:')
    
    final_list = [re.sub('[^a-zA-Z0-9'+str(except_special_chars)+']+', '', _) for _ in a]
    
    print final_list
    

    然后用户输入引号'之间的特殊字符,必要时使用转义\

    【讨论】:

    • 无需拨打str
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多