如何仅保留字符串的字母数字字符?

时间:2019-07-18 10:03:30

标签: python regex

如何在字符串中保留字母数字字符。

正则表达式

def process_text(text):
    """
    Remove special characters
    Keep Alpha numeric + Space

    """    
    pattern = r'[^a-zA-Z0-9\s]'         
    text = re.sub(pattern,' ',text)
    text = " ".join(text.split())
    return text

示例字符串

RegExr was created by gskinner34 in the summer of 69 :-).

预期产量

RegExr was created by gskinner34 in the summer of

1 个答案:

答案 0 :(得分:1)

这可能有帮助:

def process_text(text):
    from string import ascii_letters  as al
    return ' '.join(i for i in text.split() if any(j for j in al if j in i))
s = 'RegExr was created by gskinner34 in the summer of 69.'
print(process_text(s))

输出

'RegExr was created by gskinner34 in the summer of'