Thread: How can i add two backslashes to a string?

  1. #1
    Registered User
    Join Date
    Jun 2005

    Unhappy How can i add two backslashes to a string?


    i'm having trouble putting two backslashes in a string, here's what I was trying to do.. I needed to replace the single backslash in a file path with two backslashes, I have written a little method to do something similar already. for example:

    string filelocation = Regex.Replace(prelocation,"\"","");

    will replace all double quotes in the string with nothing (in another word it takes out the double quotes) and i know this works

    however, with backslashes, it doesn't apear to work...for example

    string filelocation = Regex.Replace(prelocation,"\\","\\\\");
    doesnt work. the program stop with an error that says
    "Additional information: parsing "\" - Illegal \ at end of pattern."

    I've also even tried

    string filelocation = Regex.Replace(prelocation,@"\",@"\\");
    which also gives the same error

    any help is appreciated!!

  2. #2
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    string filelocation = Regex.Replace(prelocation,"\\","\\\\");
    Well this is where it gets hairy.

    \ - in C#, this is the escape character
    \\ - in C#, this is the "\" character

    \ - in regular expressions, this is the escape character
    \\ - in regular expressions, this is the "\" character

    Now, your C# code is passed to the regular expression library, so it's actually escaped twice!

    So, what you need to pass in isn't just "\\", but "\\\\". First, "\\\\" in C# is converted to two real double slashes ("\\"). Then, those two slashes are passed to the regex library, which sees them as "\".

    So this should solve your problem:
    string filelocation = Regex.Replace(prelocation,"\\\\","\\\\\\\\");

  3. #3
    Registered User
    Join Date
    Jan 2004
    Why not just use

    string filelocation = prelocation.Replace("@\",@"\\");

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  3. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  4. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 02:54 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM