0

I have this string

string s = "<textarea>\r\n</textarea>";

And I want to replace the textarea content dynamically, trying it like this:

Regex regex = new Regex("(<textarea.*?>)(.*)(</textarea>)");
string a = regex.Replace(s, "$1new value$3");

Yet this does not procedure the output I want, which should be: <textarea>new value</textarea>. It just produces

<textarea>
</textarea>

How can I fix it?

user3182508
  • 129
  • 3
  • 11
  • It appears to be an XML string that you're trying to work with - consider using `XmlDocument` or `XDocument` as those classes are specifically designed for it. – LB2 May 12 '14 at 13:41
  • As @LB2 said, anyone looking to parse an XML-type string should see this: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – DLeh May 12 '14 at 13:48

2 Answers2

5

Use RegexOptions.SingleLine mode. Otherwise . does not match newlines.

According to the documentation:

Singleline Specifies single-line mode. Changes the meaning of the dot (.) so it matches every character (instead of every character except \n).

falsetru
  • 357,413
  • 63
  • 732
  • 636
3

.* will stop when it encounters a \n.

So use RegexOptions.MultiLine option.

Or just change your regex to:

(?m)(<textarea.*?>)(.*)(</textarea>)

(?m) is inline multiline modifier.

Edit:

Sorry It should've been RegexOptions.SingleLine. I was confused since I use regex only in javascript on a large basis.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • Tried using `Regex regex = new Regex("()(.*)()", RegexOptions.Multiline);` still does not give the desired result... Note: the string is `\r\n` and not `\\r\\n` – user3182508 May 12 '14 at 13:43
  • @user3182508 I think Amit got the check backwards, should be `SingleLine`. –  May 12 '14 at 13:47