locked
Replacing \ with / using Regex.Replace C#

    Question

  •  Hi

    I am trying to convert

    c:\demo\numbers.txt

    to

    c/demo/numbers.txt

    my code looks lie this

        string
    sfupath = c:\demo\numbers.txt;

            sfupath = Regex.Replace(sfupath, ":", "");

            sfupath = Regex.Replace(sfupath, "\"", "/");

            textBox1.Text = sfupath;

    I get the following

    c\demonumbers.txt

    As you can see it has removed the : and the last \ and not replaced the \ with /.

    I need to replace the \ with  / globaly as I could get diffrent path lengths eg c:\demo\numbers.txt may be c:\demo\newfolder\numbers.txt.

    All the articals on the net tell me that it is because \ and / are special characters but I cant seem to tell c# not to use them as special characters.

    Thank you

    Graham





    Wednesday, October 22, 2008 8:51 AM

Answers

  • You need to escape special characters with a backslash. Since \ is a special character you would use: \\. In your 2nd replace you have "\"" - that is incorrect. It just so happens that a double quote is also a special character, so your \" is really returning a double quote character and not a backslash character.

    To get this working properly you would need to change Regex.Replace(sfupath, "\"", "/"); to this:

    Regex.Replace(sfupath, @"\\""/"); 

    Actually, it really should be: Regex.Replace(sfupath, "\\\\", "/");

    FYI 4 backslashes are needed in this case to represent a single backslash in regex. Earlier I said you needed 2, but then to represent the escape character (a backslash) you need another 2! To avoid so many backslashes and for clarity you can use the @ symbol shortcut in C# to prevent escape sequences from being processed, as I did above. For more info on the verbatim strings with the @ symbol you can visit this link.

    That being said, why use Regex.Replace when you can use String.Replace? It doesn't seem like you have a complex replacement pattern that would really need regex. You can use it if you really wanted to but this would work fine:

    sfupath = sfupath.Replace(":""").Replace(@"\""/"); 

    When using String.Replace you'll notice that 2 backslashes are needed instead of the 4 that are needed to satisfy regex requirements. Or, 1 backslash instead of 2 when using verbatim strings.

    Document my code? Why do you think it's called "code"?
    • Marked as answer by Graham71 Thursday, October 23, 2008 5:44 AM
    Wednesday, October 22, 2008 3:11 PM

All replies

  • You need to escape special characters with a backslash. Since \ is a special character you would use: \\. In your 2nd replace you have "\"" - that is incorrect. It just so happens that a double quote is also a special character, so your \" is really returning a double quote character and not a backslash character.

    To get this working properly you would need to change Regex.Replace(sfupath, "\"", "/"); to this:

    Regex.Replace(sfupath, @"\\""/"); 

    Actually, it really should be: Regex.Replace(sfupath, "\\\\", "/");

    FYI 4 backslashes are needed in this case to represent a single backslash in regex. Earlier I said you needed 2, but then to represent the escape character (a backslash) you need another 2! To avoid so many backslashes and for clarity you can use the @ symbol shortcut in C# to prevent escape sequences from being processed, as I did above. For more info on the verbatim strings with the @ symbol you can visit this link.

    That being said, why use Regex.Replace when you can use String.Replace? It doesn't seem like you have a complex replacement pattern that would really need regex. You can use it if you really wanted to but this would work fine:

    sfupath = sfupath.Replace(":""").Replace(@"\""/"); 

    When using String.Replace you'll notice that 2 backslashes are needed instead of the 4 that are needed to satisfy regex requirements. Or, 1 backslash instead of 2 when using verbatim strings.

    Document my code? Why do you think it's called "code"?
    • Marked as answer by Graham71 Thursday, October 23, 2008 5:44 AM
    Wednesday, October 22, 2008 3:11 PM
  • Thank you

    I found the four \'s on the net aswell but you string replace is ver interesting what is the diffrence between the regular expresion and the string replace when do you use which one.

    your info was great and will help me

    graham
    Thursday, October 23, 2008 5:46 AM
  • The RegularExpression Replace() function will allow you to replace things more complex than just a single fixed character.

    Consider this example...

                string test = "On Monday we go to the zoo.  On Tuesday we go to the fair.  Where sould you like to go Wednesday.";  
                string pattern = "Monday|Tuesday|Wednesday";  
                Console.WriteLine("{0}", Regex.Replace(test, pattern, "<dayOfWeek>", RegexOptions.IgnoreCase));  
     

    This is a little more difficult to do with String.Replace, but pretty simple with Regex.  The String version would look like this...

            Console.WriteLine("{0}",test.Replace("Monday","<dayOfWeek>").Replace("Tuesday","<dayOfWeek>").Replace("Wednesday","<dayOfWeek>"));

    So, even this can be done both ways, but the Regex demonstrates greater flexibility.  To add days to the Regex version, you modify the pattern (data).  But to add days to the String.Replace() version, you have to modify the code.

    Regex.Replace() also offers an Evaluator function.  If you were to write a function with the following signature...

        string Evaluate(Match m)
        {
            return "<dayOfWeek>";
        }

    ... you could use this in Regex.Replace() to replace all occurances of the match with "<dayOfWeek>".  But, better yet, you can actually examine the Match value and return a different replacement value depending upon what matched.  For example...

                string test = "Funk is a strange kind of music.  Listen only briefly and you won't want to keep your seat.";  
                string pattern = @"\b\w+\b";  
                Console.WriteLine("{0}", Regex.Replace(test, pattern, Evaluate, RegexOptions.IgnoreCase));  
              
    ...  
     
            private string Evaluate(Match m)  
            {  
                string ret = m.Value;  
                if(m.Value.Length == 4)  
                {  
                    if(m.Value.StartsWith("f",StringComparison.OrdinalIgnoreCase)  
                        || m.Value.StartsWith("s",StringComparison.OrdinalIgnoreCase))  
                        ret = m.Value[0] + "xxx";  
                }  
                return ret;  
            }  
     

    So, Regex.Replace() is very powerful.  But, String.Replace() is simple and fast.  Pick your tools appropriately.

    Les Potter, Xalnix Corporation, Yet Another C# Blog
    Thursday, October 23, 2008 1:33 PM