Skip to main content
 首页 » 编程设计

python之用正则表达式替换所有非字母/数字

2024年09月03日30me-sa

我有字符串 'hello (new)' 并且我想删除所有非数字和字母。一种方法是找到所有字母并加入它们:

>>> ''.join(re.findall(r'[a-zA-Z0-0]', 'hello (new)')) 
'hellonew' 

我如何做相反的事情,即将所有非字符替换为 ''?到目前为止,我有:

>>> re.sub(r'^[a-zA-Z0-9]+', '', 'hello (new)') 
' (new)' 

但是有点偏了。

请您参考如下方法:

您应该改用否定字符类并移除前面的 anchor :

re.sub(r'[^a-z0-9]+', '', 'hello (new)', re.IGNORECASE)