简体   繁体   English

Regex.Replace()用于替换整个事件

[英]Regex.Replace() for replacing the whole occurrence

Am using regex.Replace() to replace the whole occurrence of a string.. so I gave like Regex.Replace(str,@stringToReplace,"**"); 我使用regex.Replace()来替换整个字符串的出现..所以我给了Regex.Replace(str,@ stringToReplace,“**”); where stringToReplace = @"session" + "\\b"; 其中stringToReplace = @“session”+“\\ b”;

if i give like that its not replacing.. but if i give like Regex.Replace(str,@"session\\b","**"); 如果我这样给它不替换..但如果我给像Regex.Replace(str,@“session \\ b”,“**”); then its working.. how to avoid this.. i want to pass value which will be set dynamically.. 然后它的工作..如何避免这..我想传递将动态设置的值..

Thanks nimmi 谢谢nimmi

尝试

stringToReplace = @"session" + @"\b";

The @ here means a verbatim string literal . @ here表示逐字字符串文字

When you write "\\b" without the @ it means the backspace character, ie the character with ASCII code 8. You want the string consisting of a backslash followed by a b , which means a word boundary when in a regular expression. 当你在没有@情况下写“\\ b”时,它表示退格字符,即带有ASCII码8的字符。你想要一个由反斜杠后跟一个b组成的字符串,这意味着在正则表达式中有一个单词边界。

To get this you need to either escape the backslash to make it a literal backslash: "\\\\b" or make the second string also into a verbatim string literal: @"\\b" . 要得到这个,你需要转义反斜杠使其成为字面反斜杠: "\\\\b"或将第二个字符串也变成逐字字符串文字: @"\\b" Note also that the @ in @"session" (without the \\b ) doesn't actually have an effect, although there is no harm in leaving it there. 另请注意, @ in @"session" (没有\\b )实际上没有效果,尽管将它留在那里没有任何害处。

stringToReplace = "session" + @"\b";

@"session" + "\\b" and @"session\\b" @“session”+“\\ b”和@“session \\ b”

are not the same string. 字符串不一样。 In the first case "\\b" you don't treat the slash as a slash but as an escape parameter. 在第一种情况下,“\\ b”不会将斜杠视为斜杠,而是将其视为转义参数。 In the second case you do. 在第二种情况下你做。

So @"session" + @"\\b" should bring the same result 所以@“session”+ @“\\ b”应该带来相同的结果

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

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