20

It seems simple enough, right? Well, I don't know.

Here's the code I'm trying:

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

However, I'm receiving an error,

ArgumentException was unhandled - parsing "\" - Illegal \ at end of pattern.

How do I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Johnny
  • 373
  • 1
  • 6
  • 11
  • 6
    Unless you're doing something more complicated in the same pattern, have you considered `input = input.Replace(@"\", @"\\");`? – Kobi May 24 '11 at 04:57

6 Answers6

25

The first one should be "\\\\", not "\\". It works like this:

  • You have written "\\".
  • This translates to the sequence \ in a string.
  • The regex engine then reads this, which translates as backslash which isn't escaping anything, so it throws an error.

With regex, it's much easier to use a "verbatim string". In this case the verbatim string would be @"\\". When using verbatim strings you only have to consider escaping for the regex engine, as backslashes are treated literally. The second string will also be @"\\", as it will not be interpreted by the regex engine.

porges
  • 30,133
  • 4
  • 83
  • 114
8

If you want to replace one backslash with two, it might be clearer to eliminate one level of escaping in the regular expression by using @"..." as the format for your string literals, also known as a verbatim string. It is then easier to see that

string output = Regex.Replace(input, @"\\", @"\\");

is a replacement from \ to \\.

Aaa
  • 1,854
  • 12
  • 18
6

I know it's too late to help you, maybe someone else will benefit from this. Anyway this worked for me:

text = text.Replace(@"\",@"\\");

and I find it even more simplier.

Cheers!

igop
  • 61
  • 1
  • 3
4
 var result = Regex.Replace(@"afd\tas\asfd\", @"\\", @"\\");

The first parameter is string \\ which is \ in regex.
The second parameter is not processed by regex, so it will put it as is, when replacing.

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
3

If you intend to use the input in a regex pattern later, it can be a good idea to use Regex.Encode.

input = Regex.Escape(input);
Allrameest
  • 4,364
  • 2
  • 34
  • 50
1

I have tried all these examples, but without success. I had a "//" and I didn't want to change it. I only needed to change the "/"

This regex helped me:

  • string myString = "https://example.com/example/example/example";

  • string result = Regex.Replace(myString, @"(?<!/)/(?!/)", "//");

  • and I got - "https://example.com//example//example//example"

Vlad
  • 11
  • 3