正则表达式匹配任何非单词字符,但减去

Rem*_*emy 15 .net regex

我需要清理文件名.所以我有这个代码:

//\W_ is any non-word character (not [^a-zA-Z0-9_]).
Regex regex = new Regex(@"[\W_]+");
return regex.Replace(source, replacement);
Run Code Online (Sandbox Code Playgroud)

这工作正常,但现在我不想删除减号( - ),所以我将正则表达式更改为:

[\W_^-]+
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我错过了什么?

Ous*_*ama 20

尝试使用此正则表达式:

[^\w-]+
Run Code Online (Sandbox Code Playgroud)

编辑:

似乎正确的正则表达式是:

[^a-zA-Z0-9-]+
Run Code Online (Sandbox Code Playgroud)

  • 我认为这部分不正确,因为它与下划线不匹配。 (2认同)