0

I am trying to replace every occurrence of "]}]" (ignore the quotes) using the Regex object in C#.

I have set up the Regex Escape value like this:

var regexReplaceVar = new Regex(Regex.Escape("]}]")); 

I then call the replace method as shown below:

myEditedString = regexReplaceVar.Replace(startString, sringToInsert, 1);

It does not appear to be working the way I think it would. Are the characters I am attempting to replace special to Regular Expressions? Should they be modified to have them be taken as literals?

Thanks in advance.

3
  • 2
    Why not use string.Replace? Commented Dec 26, 2013 at 20:12
  • 1
    This form Replace(input,replacement,count) just does count replacements. Is that the problem? Commented Dec 26, 2013 at 20:47
  • "It does not appear to be working the way I think it would." Describe how you think it should work, and how it is working. Commented Dec 26, 2013 at 21:04

2 Answers 2

3

Description:

All of the characters you are seeking must be escaped in C# Regex.

Regex:

\]\}\]

C#:

Regex regexObj = new Regex(@"\]\}\]", RegexOptions.IgnoreCase);
string result = regexObj.Replace(subjectString, replaceWith);
Console.WriteLine(result);

result holds the replaced string, this is important because subjectString doesn't change

MSDN on Regex.Replace

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

1 Comment

I don't think as a stand alone regex string combination, that any of these characters need to be escaped.
0

Whenever I use regex I use this page to test them: http://rubular.com/

If you feel uncertain how to use regex I recommend the following article and page: http://www.regular-expressions.info/replacetutorial.html

And if you are using common regex expression e.g time and date formatting you can search for pre-formatted expressions here: regexlib.com

2 Comments

Not sure, but don't think this is true in Dot-Net's regex 'Replace` method. ie: its not like ^..$
You are not correct. the string "asd]}]asd" will match the OP's expression. It's looking for "]}]" anywhere in the string.

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.