-2

I have a situation where I have a string in which I have to replace a part that lies between special characters. I can do the same using substrings and length,but that is the dirty way. Is there any better way of doing this using regex?

e.g. of the string is

string str1 = "This is the <![CDATA[ SampleDataThatNeedsToBeReplaced ]]";
string repl = "Replacement Text";

I need a regex to get the output as

This is the Replacement Text

I did try a few regex like the following

 result = Regex.Replace(str1, @"(?<=CDATA\[)(\w+?)(?=\]\])", repl);

I also tried

Regex x = new Regex("(\\[CDATA\\])(.*?)(\\[\\]\\]\\])");
string Result = str1.Replace(text, "$1" + repl + "$3");

did not get any results. Any help is appreciated.

Gautam
  • 1,628
  • 8
  • 29
  • 65
  • why don't you use `string.Replace` method then seems like that would be easier vs you struggling with `Regex` – MethodMan Jul 06 '16 at 21:03
  • thats what I am doing right now, but it looks very dirty since I have to get the start index, end index, then substrings then concatenate. So if it can be done using regex.. the dirty part can be skipped – Gautam Jul 06 '16 at 21:04
  • so where is `text` coming from.. when you show code please show all examples of your string and what your expected outcome is supposed to look like – MethodMan Jul 06 '16 at 21:07
  • 1
    Seems like that text comes from an xml. If so, you can use an xml parser... http://stackoverflow.com/questions/2784183/what-does-cdata-in-xml-mean – Eser Jul 06 '16 at 21:17

1 Answers1

1
Regex.Replace (
    "This is the <![CDATA[ SampleDataThatNeedsToBeReplaced ]]",
    @"<!\[CDATA\[(.+)]]",
    "Replacement Text");

Note that in case you need it ; the old text (between the inner brackets) is available as group1 (and so can be referenced via $1)

Sehnsucht
  • 4,919
  • 14
  • 27