0

I try to check if string is Match GetInvalidFileNameChars()

i would like to use regex

So i put the chars of GetInvalidFileNameChars() into a string and then check

if Regex.IsMatch(id, stringInvalidFileName)

I thought if id = "4711./" then Regex.IsMatch(id, stringInvalidFileName)

should be true, but it's false

What is my mistake, why is it false ?! Thanks in advance

Andrei
  • 55,890
  • 9
  • 87
  • 108
Barnabas
  • 3
  • 1

1 Answers1

2

Why use a regex?

This will work fine:

string s = "4711./";
if (Path.GetInvalidFileNameChars().Any( c => s.Contains(c))

As Rawling points out below, when you're dealing with large strings it might be more efficient to use Intersect instead:

string longString = "Something much, much longer than this";
if (longString.Intersect(Path.GetInvalidFileNameChars()).Any())

For relatively short strings (file paths, for example) there's probably little if any benefit. I'd prefer the first option, as it more clearly conveys the code's intent, in my opinion.

Community
  • 1
  • 1
Rik
  • 28,507
  • 14
  • 48
  • 67
  • Or you could use `Intersect` and not be `O(n^2)` :p – Rawling Oct 14 '15 at 11:16
  • `Contains` returns immediately once a match is found, where as `Intersect` always needs to enumerate the entire string, so I doubt `Intersect` will give you any real benefits. – Rik Oct 14 '15 at 11:44
  • `Intersect(...).Any()` stops as soon as a match is found, and only iterates each input once. – Rawling Oct 14 '15 at 12:45