简体   繁体   中英

Replacing text with regex using ".*" and $1

string pattern = @"<p>.*<br>";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
r.Replace(pattern, "<p>$1</p>");

The above code is supposed to find and replace the following <p> and <br> tags with <p> and <p> while keeping the text in between them. This will replace <p> and <br> but will replace the middle with "$1" instead of the appropriate text. I'm used to writing RE in Python which seems to be quite different.

Problems to solve:

  • Add () in pattern to get capture group
  • Pass input to replace method
  • Store result in variable (note: C# strings are immutable).

Fixed code:

string pattern = @"<p>(.*)<br>";
Regex rgx = new Regex(pattern);
string output = rgx.Replace(input, "<p>$1</p>");

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