How to exclude a character from a regex group?

atp*_*atp 24 python regex

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)

+将简单地导致任何连续匹配的字符的运行同时匹配(并被替换).

  • +1你是对的,把你的答案删除,因为你的封面我认为他想要的......匹配任何不是数字,字母或连字符的字符. (2认同)

Ned*_*der 6

\w 匹配字母数字,添加连字符,然后否定整个集合: r"[^\w-]"