python regex,删除所有除\ d \ s \ w

gur*_*gui 0 python regex

如何制作一个python RegEx来删除文本中除以下字符外的所有字符: \d \w \s

我尝试过这样的事情:

import re
re.sub(r'\W*\D*\S*', '', 'this is my<\n test <+-,1345.;>')
Run Code Online (Sandbox Code Playgroud)

但这给了我一个空字符串。我想得到:this is my test ,1234.。我也想保留,.

Mar*_*ers 5

使用反向字符类:

re.sub(r'[^., \t\w]*', '', 'this is my<\n test <+-,1345.;>')
Run Code Online (Sandbox Code Playgroud)

演示:

>>> re.sub(r'[^., \t\w]*', '', 'this is my<\n test <+-,1345.;>')
'this is my test ,1345.'
Run Code Online (Sandbox Code Playgroud)

\W\S\D类是太宽\D例如,匹配大部分\w匹配项,删除掉落的所有内容都\D将删除过多内容。任何不是数字的东西都将被删除,但是您想保留字母和标点符号。

\s用文字空间和制表符代替,因为您想删除换行符(也包括空格),所以我添加了.,所以也保留了它们。\d也不需要,\w是的超集\d