简体   繁体   中英

Odd behaviour replacing “\”

I have this issue in which I have a strnig with among other things the literal expression "\\\\" on several occasions and I want to replace it with "\\" , when I try to replace it with string.replace, only replcaes the first occurrence, and if I do it with regular expression it doesn't replace it at all

I checked with some RegEx Testers online and supposedly my code is ok, returns what I meant to, but my code doesn't work at all

With string.replace

example = "\\\\url.com\\place\\anotherplace\\extraplace\\";

example = example.replace("\\\\","\\");

returns example == "\\url.com\\place\\anotherplace\\extraplace\\";

With RegEx

example = Regex.Replace(example,"\\\\","\\");

returns example = "\\\\url.com\\place\\anotherplace\\extraplace\\";

It is the same case if I use literals (On the Replace function parameters use (@"\\\\", @"\\") gives the same result as above).

Thanks!

EDIT:

I think my ultimate goal was confusing so I'll update it here, what I want to do is:

Input: variable that holds the string: "\\\\\\\\url.com\\\\place\\\\anotherplace\\\\extraplace\\\\"

Process

Output variable that holds the string "\\\\url.com\\place\\anotherplace\\extraplace\\" (so I can send it to ffmpeg and it recognizes it as a valid route)

change this:

example = "\\\\url.com\\place\\anotherplace\\extraplace\\"; 

to this

example = @"\\\\url.com\\place\\anotherplace\\extraplace\\"; 

It wasn't the Regex.Replace parameters that was the problem.

You only have one occurrence of \\\\\\\\ in your string. So it is doing exactly what you asked it to do.

Without escaping (ie without adding extra /'s)

  • What is your actual input?
  • What is your desired output?

您应该将其更改为以下内容

example = example.replace(@"\\", @"\");

That appears to be the expected behavior.

In the String.Replace case: Initially, example contains a string that starts with two backslashes, and contains a few single backslashes elsewhere in the string. You then attempted to replace all occurrences of double backslashes with a single backslash, which worked and produced a string that starts with a single backslash and contains a few single backslashes elsewhere in the string.

In the Regex.Replace case: The original contents of example are irrelevant in this case. Your regex pattern is a double backslash, which when interpreted as a regex pattern, means "find a single backslash". You then replace this pattern with a single backslash, which results in no change to the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM