1

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?

6
  • When you say special characters, what do you mean? What makes them "special" for your use case?
    – Oded
    Apr 12, 2013 at 19:30
  • Brackets specifically break our system so we cannot allow a file with brackets be uploaded. Apr 12, 2013 at 19:32
  • By "brackets", do you mean the square ones [ and ]? (The {} are called curly brackets by some.)
    – Ryan M
    Apr 12, 2013 at 19:32
  • Both are illegal but {curly} is being found by any method I use, square [brackets] are the problem. Apr 12, 2013 at 19:33
  • Try a regular expression test page, like this. You may also want to look at Regex Editor, an extension for Visual Studio.
    – HABO
    Apr 12, 2013 at 19:36

2 Answers 2

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

Works for me:

string test = "aoeu[aoeu";

Match m = Regex.Match(test, @"[\[\]{}!@#]");
// m.Success == true
3
  • This solves my bracket problem but how can I put a double quote " into the string literal to be checked? Apr 12, 2013 at 19:45
  • Double it: @"[\[\]'~#%&*{}<>:?/|\\@!""]"
    – Ryan M
    Apr 12, 2013 at 19:47
  • 1
    @TimeTravelMishap, double it. The @ symbol indicates the start of a verbatim string literal. Apr 12, 2013 at 19:47
1

Your solution

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

is perfect already. Leave escaping regular expressions to Houdini.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.