1

Can someone please explain how to get this regex working? I'm trying to take this string:

"Test0/1"

and turn it into:

"Test0\/1"

I'm using this, but it is not working:

var test = Regex.Replace("Test0/1", @"/", @"\/");

It keeps giving me

"Test0\\/1"

Then I want to take the results of the string and put it into a Regex statement like so:

var match  = new Regex(test).Match(myString);

So the string 'test' has to be a valid regex statement.

Basically what I'm trying to do is take a list of interfaces off a device, create a regex statement out of them and then use that regex to compare results for other things in my code. Because of the way interfaces are formatted "FastEthernet0/1" for example, it is causing my regex to fail because you have to escape all forward slashes. I have to build this regex on the fly though because every device will have a different set of interfaces.

  • 5
    If you're seeing `"Test0\\/1"` in the debugger, then don't worry. The string is still correct. Try printing it to the console or clicking on the magnifying glass icon to the left of the string you see. – Nolonar Mar 13 '13 at 16:16
  • I do see that in the debugger, but I'm not printing it out. I'm using the results to put into Regex(). So it needs to be a valid Regex statement. That is why I'm trying to escape the forward slash. –  Mar 13 '13 at 16:17
  • @KyleRogers the debugger is just displaying it that way. – Daniel A. White Mar 13 '13 at 16:17
  • To begin with, `@"\/"` is not a valid escape sequence for Regex. It should be `@"\\/"` (to match for a literal `\ `, then a literal `/`), or `"\\\\/"` (which matches the same as before, but without using the verbatim `@` character) – Nolonar Mar 13 '13 at 16:24
  • @Nolonar I'm trying to match the literal '/' with regex. –  Mar 13 '13 at 21:17
  • @KyleRogers The literal `/` (forward slash) is not used in `Regex`, which means you can match it the *good ol' way*, with a simple `"/"` – Nolonar Mar 13 '13 at 23:39
  • @Nolonar http://rubular.com/r/5bHUCDhv2m My regex is C# doesn't work as well as on this website. I'm not a regex expert, but I've had to escape them for all my expressions thus far. –  Mar 14 '13 at 01:00
  • @KyleRogers I just tested it under Visual Studio: `Regex.IsMatch("Test0/1", "/") == true`. – Nolonar Mar 14 '13 at 07:47

1 Answers1

1

This is a function of Visual Studio automatically escaping the \ on your behalf. Look at the following question: What's the use/meaning of the @ character in variable names in C#?. Removing the @ symbol from @"\" turns the string into "\\".

Community
  • 1
  • 1
Ryan Gates
  • 4,501
  • 6
  • 50
  • 90