Remy
Remy

Reputation: 12703

Regex to match any non-alphanumeric character but the minus

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?

Upvotes: 19

Views: 22511

Answers (2)

Oussama Jilal
Oussama Jilal

Reputation: 7739

Try using this regular expression :

[^\w-]+

Edit :

Seems that the right regular expression is :

[^a-zA-Z0-9-]+

Upvotes: 27

Kash
Kash

Reputation: 9019

Just inverting what you want and what you don't:

[^a-zA-Z0-9-]+

RegexPal link for this.

Upvotes: 4

Related Questions