Share via


Replacing forward-slash with a back-slash

Question

Wednesday, September 19, 2012 7:50 PM

Hi,

I have this snippet written to replace all forward-slashes with a back-slash character. Console output as well as the debugger - do not show it as replaced.

 

static void Main(string[] args)
        {
            string filename = "/test/";
            string formattedFileName = FormatFileName(filename);
        }

public static string FormatFileName(string fileName)
        {
            Console.WriteLine(string.Format(@"Test fileName: {0}", fileName));

            string fileNameTemp = fileName;

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

            Console.WriteLine(string.Format(@"Test fileName: {0}", fileNameTemp));

            return fileNameTemp;
        }

 

and here's the output:

Test fileName: /test/
Test fileName: /test/
Press any key to continue . . .

As you can see, no change in the input string. Anyone knows how to fix this?

Thanks!

All replies (3)

Wednesday, September 19, 2012 8:23 PM âś…Answered

@ remond724

in case you're wondering, here's where you went wrong:

http://msdn.microsoft.com/en-us/library/e7f5w83z.aspx "Regex.Replace Method (String, String, String)"

public static string Replace(     //  <===  returns a String
    string input,
    string pattern,
    string replacement
)

Parameters

input              Type: System.String     The string to search for a match.

pattern           Type: System.String     The regular expression pattern to match.

replacement   Type: System.String      The replacement string.

Return Value     Type: System.String A new string that is identical to the input string, except that the replacement string takes the place of each matched string.

you MUST assign the returned string.

g.


Wednesday, September 19, 2012 8:11 PM

@ remond724

your code works ... but you MUST assign the result:

void Main()
{
    string filename = "/test/"; 
    string formattedFileName = FormatFileName(filename); 

}

public static string FormatFileName(string fileName) 
{ 
    Console.WriteLine(string.Format(@"Test fileName: {0}", fileName)); 
    string fileNameTemp = fileName; 
    string regexResult = 
    Regex.Replace(fileNameTemp, "/", @"\"); 
    Console.WriteLine(string.Format(@"Test fileName: {0}", fileNameTemp)); 
    Console.WriteLine(string.Format(@"Test fileName: {0}", regexResult)); 
    return fileNameTemp; 
}

output:

Test fileName: /test/
Test fileName: /test/
Test fileName: \test\

g.


Wednesday, September 19, 2012 8:41 PM

Thanks Gerry!