Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match any non-alphanumeric character but the minus

Tags:

.net

regex

I need to clean up filenames. So I have this code:

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

This works fine, but now I don't want to remove the minus (-), so I changed the regex to this:

[\W_^-]+

But that does not work. What did I miss?

like image 453
Remy Avatar asked Aug 29 '12 15:08

Remy


1 Answers

Try using this regular expression :

[^\w-]+

Edit :

Seems that the right regular expression is :

[^a-zA-Z0-9-]+
like image 191
Oussama Jilal Avatar answered Sep 22 '22 12:09

Oussama Jilal