Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace() for replacing the whole occurrence

Tags:

c#

regex

Am using regex.Replace() to replace the whole occurrence of a string.. so I gave like Regex.Replace(str,@stringToReplace,"**"); where stringToReplace = @"session" + "\b";

if i give like that its not replacing.. but if i give like Regex.Replace(str,@"session\b","**"); then its working.. how to avoid this.. i want to pass value which will be set dynamically..

Thanks nimmi

like image 996
Nimmi Avatar asked Feb 28 '23 02:02

Nimmi


2 Answers

try

stringToReplace = @"session" + @"\b";
like image 180
Sam Holder Avatar answered Mar 06 '23 18:03

Sam Holder


The @ here means a verbatim string literal.

When you write "\b" without the @ it means the backspace character, i.e. 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.

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". Note also that the @ in @"session" (without the \b) doesn't actually have an effect, although there is no harm in leaving it there.

stringToReplace = "session" + @"\b";
like image 20
Mark Byers Avatar answered Mar 06 '23 17:03

Mark Byers