Click here to Skip to main content
14,327,564 members
Rate this:
Please Sign up or sign in to vote.
Hi, my goal is it to make wildcard to regex.

I want to escape all regex caracters, except * and ?

this is what i have so far:
str = Regex.Escape(str);
str.Replace(@"\*", @"*");
str.Replace(@"\?", @"?");

when i insert foo*.xml I expect an output of foo*\.xml (escape the puncuration). But instead I get foo\\*\\.xml which didnt escaped the dot, but added 2 escaped backslashes in it

Please help, thanks.

Rate this:
Please Sign up or sign in to vote.

Solution 1

Replace does not change the original string, it only returns a new string.

Try this instead:
str = Regex.Escape(str);
str = str.Replace(@"\*", @"*");
str = str.Replace(@"\?", @"?");

You say that you see two backslashes, but there are not really two backslashes. The double backslash is just an escape sequence for the backslash in the string, but the backslash won't be escaped when doing the regex operation.
More about escape sequences:[^]
Whether you see two backslashes or not, depends on the way you display the string -- if you view it in the debugger, you'll see two backslashes. If you output the string using Console.WriteLine, you'll only see one.
iLembus 7-Feb-15 12:24pm
Oh no, they did the old switcheroo again.
But i still get a escaped slash in front of the dot. (escaped slash, dot not escaped)
Thomas Daniels 7-Feb-15 12:29pm
I edited my answer.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Okay, I just found out that Directory.GetFiles(path, wildcard, searchOption) doesn't take Regex, it takes regular Wildcards.

This whole Regex to Wildcard junk was completely waste of my time xD

but thanks guys.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100