I’m trying to remove illegal chars from a string that represent path or filename in windows.
Here is the code i used for testing:
string pattern = "([\", \\, <,>, :, /, ?,|,*])";
string[] names = { "o\"ne", "t\\wo", "thr<ee", "fo>ur", "fi:ve", "si/x", "sev?en", "ei|ght", "ni*ne" };
foreach (String name in names)
{
Console.WriteLine(Regex.Replace(name, pattern, String.Empty));
}
I get all prints okay, except “two” that writes like this: t\wo.
I’ve tried putting an asterisk outside the parenthesis and got the same result.
What should i do?
Thank You.
You’ll need to double escape the backslash in your regex pattern; the reason being that the backslash character is used to indicate character groups in regexes (e.g.,
\dto represent digits). To match on a backslash, you use the notation\\. This then has to be escaped in the .NET string.In short, change
\\to\\\\.