通过删除符号清理字符串

时间:2017-12-27 08:56:39

标签: python regex

我必须清除一个删除特殊符号/#$%^&*@0123456789的字符串,只要它们通过列表中没有的字母或符号彼此分开。 例如:

H8e%&l6&%l@8095o a@/9^65$n228d w%e60$$#&9l3@/c6o5m3e --> Hello and welcome
I1^/0^^@9t #$%% i/@4#s 11P17/9$M 5^&* a^$45$5$0n&##^4d 6^&&* I $%^$%^ a8@@94%3*m t3120i36&^1r2&^##0e&^d ---> It #$%% is 11PM 5^&* and 6^&&* I $%^$%^ am tired
,. a3%2%1/3$s*0. d8^! -->,. as. d!
##%12Symbols on the left must remain untouched --> ##%12Symbols on the left must remain untouched

我发现可以使用re.sub

import re
def _correct_message(message):
    new_final_string = re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', message)
    return new_final_string

但我不喜欢我必须手动添加不在列表.!.?中的符号这一事实。是否可以在没有regex的情况下制作它?

1 个答案:

答案 0 :(得分:0)

这是我能得到的最接近的:

 (\W+|\d{1,}(?!\d\[A-Za-z]))(?![A-Za-z]{2,})

只需用空格替换所有匹配

相关问题