I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python). How can I change this regular expression to match any non-alphanumeric char except the hyphen?
re.compile('[\W_]')
Run Code Online (Sandbox Code Playgroud)
Thanks.
eld*_*his 27
你可以使用一个否定的字符类代替:
re.compile(r"[^a-zA-Z0-9-]")
Run Code Online (Sandbox Code Playgroud)
这将匹配不在字母数字范围或连字符中的任何内容.它根据您当前的正则表达式匹配下划线.
>>> r = re.compile(r"[^a-zA-Z0-9-]")
>>> s = "some#%te_xt&with--##%--5 hy-phens *#"
>>> r.sub("",s)
'sometextwith----5hy-phens'
Run Code Online (Sandbox Code Playgroud)
请注意,这也替换了空格(可能肯定是你想要的).
编辑: SilentGhost建议使用量词处理引擎可能更便宜,在这种情况下,您可以简单地使用:
re.compile(r"[^a-zA-Z0-9-]+")
Run Code Online (Sandbox Code Playgroud)
这+将简单地导致任何连续匹配的字符的运行同时匹配(并被替换).