1

I am using Regex replace as below :

string test = "[abc] Sends the employee mail. [twist] Sends the employee mail.";
test = Regex.Replace(test, "[twist]", "hello");

And the result is coming as :

test = "[abc] Sendhello hellohe employee mahellol. [hellohellohellohellohello] Sendhello hellohe employee mahellol."

Where as it should just replace [twist] string with hello.

What is going wrong here.

1
  • Try using one of the many RegEx parsers out there first. Will explain it for you instantly in most cases. :) Commented Aug 9, 2013 at 8:56

3 Answers 3

3

You must escape the brackets (at least the opening one). Change

"[twist]"

to

"\\[twist\\]"

or, using a verbatim literal to avoid the double \,

@"\[twist\]"

[twist] is interpreted as any of the t, w, i, s or t character and any of them is replaced by the hello string.

Sign up to request clarification or add additional context in comments.

1 Comment

or @"\[twist\]" :-)
0

Regex.Replace(test,"\[twist\]","hello")

Comments

0

As additional useful informations, you could escape the [ as [[], so

"[[]twist]"

or you could

"\\x5btwist]"

where \x5b is the ascii code of [. Note that you need to escape the \ of \x5b because otherwise "\x5b" == "[" (the C# makes the string replacement). By escaping it instead it's the Regex that "receives" the \x5b and considers it as a [. Clearly you could disable escape sequences expansion by using the @

@"\x5btwist]"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.