0

I want to replace the textarea value with something else, using C# regex. Right now I have this:

Regex regex = new Regex("<textarea.*>(.*)</textarea>");
string s = "<textarea>test</textarea>";
string a = regex.Replace(s, "abc");

Except this prints abc instead of <textarea>abc</textarea>. I want to make it as dynamic as possible,

So something like this

<textarea rows="20" class="style">test</textarea>

Should become

<textarea rows="20" class="style">abc</textarea>

Thanks!

user3182508
  • 129
  • 3
  • 11
  • 1
    Your stars are greedy. Try making them lazy by adding question marks: `"(.*?)"` and see if you have any better luck. – tmoore82 May 01 '14 at 13:55

1 Answers1

2

You need to use capture groups and then put them in the output. Like this:

void Main()
{
  Regex regex = new Regex("(<textarea.*>)(.*)(</textarea>)");
  string s = "<textarea>test</textarea>";
  string a = regex.Replace(s, "$1abc$3");
  Console.WriteLine(a);
}
Hogan
  • 69,564
  • 10
  • 76
  • 117