简体   繁体   English

正则表达式替换为正斜杠

[英]Regex Replace with forward slash

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. 因此,字符串“ test”必须是有效的正则表达式语句。

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. 基本上,我想做的是从设备上获取接口列表,从其中创建一个regex语句,然后使用该regex比较代码中其他内容的结果。 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. 例如,由于接口格式化为“ FastEthernet0 / 1”的方式,这导致我的正则表达式失败,因为您必须转义所有正斜杠。 I have to build this regex on the fly though because every device will have a different set of interfaces. 我必须即时构建此正则表达式,因为每个设备将具有一组不同的接口。

This is a function of Visual Studio automatically escaping the \\ on your behalf. 这是Visual Studio的功能,代表您自动转义\\ Look at the following question: What's the use/meaning of the @ character in variable names in C#? 请看以下问题: C#变量名称中@字符的用途/含义是什么? . Removing the @ symbol from @"\\" turns the string into "\\\\" . @"\\"删除@符号会将字符串变成"\\\\"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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