Click here to Skip to main content
15,886,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
C#
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.

Sincerely:
Jonas
Posted

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

Try this instead:
C#
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: https://msdn.microsoft.com/en-us/library/h21280bw.aspx[^]
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.
 
Share this answer
 
v4
Comments
[no name] 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.
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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900