Garrett
Garrett

Reputation: 555

Issue with Regex Replace

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.

Upvotes: 0

Views: 169

Answers (2)

Victor Axelsson
Victor Axelsson

Reputation: 1466

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

Upvotes: 0

abc123
abc123

Reputation: 18763

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

Upvotes: 3

Related Questions