简体   繁体   中英

Replace specific part with regex

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!

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM