Jonathan Eckman
Jonathan Eckman

Reputation: 2077

C# Finding special chars in a filename

I need to simply see if there are any matches for a group of special characters in a filename I have already tried all the common regex expressions including the ones below. All of these examples will find any special character except the brackets.

Regex.Match(filename, "[\\[\\]{}!@#]");
// I even separated this out into 3 like this
Regex.Match(filename, "[");
Regex.Match(filename, "]");
Regex.Match(filename, "[{}!@#]");

filename.IndexOfAny("[]{}!@#".ToCharArray()) != -1

What gives?

Upvotes: 1

Views: 2240

Answers (2)

Colonel Panic
Colonel Panic

Reputation: 137682

Your solution

filename.IndexOfAny("[]{}!@#".ToCharArray()) != -1

is perfect already. Leave escaping regular expressions to Houdini.

Upvotes: 1

Ryan M
Ryan M

Reputation: 2112

Regex.Match(test, @"[\[\]{}!@#]");

Works for me:

string test = "aoeu[aoeu";

Match m = Regex.Match(test, @"[\[\]{}!@#]");
// m.Success == true

Upvotes: 4

Related Questions