[英]Replace line breaks except for ones between <pre> tags
我想要替換/刪除給定字符串中的所有換行符,除了嵌套在<pre>
標記內的換行符。 所以對於以下字符串:
var text = @"
Some contents which is formatted
over multiple
lines but contains a
<pre>
tag which has
also has
multiple line breaks.
</pre>
";
我想刪除所有換行符,除了嵌套在pre標簽中的換行符:
Regex.Replace(text, "\n", "<br />");
使用負向前看,您仍然可以在一行中執行:
text = Regex.Replace(text, "\n(?![^<]*</pre>)", "<br />");
這是一些測試代碼,包含多個<pre>
標簽的更好樣本:
var text = @"
Some contents which is formatted
over multiple
lines but contains a
<pre>
tag which has
also has
multiple line breaks.
</pre>
foo 1
bar 1
<pre>
tag which has
also has
multiple line breaks.
</pre>
foo 2
bar 2
";
text = Regex.Replace(text, "\n(?![^<]*</pre>)", "<br />");
Console.WriteLine(text);
輸出:
<br /> Some contents which is formatted<br /> over multiple<br /> lines but contains a <br /> <pre>
tag which has
also has
multiple line breaks.
</pre><br /> foo 1<br /> bar 1<br /> <pre>
tag which has
also has
multiple line breaks.
</pre><br /> foo 2<br /> bar 2<br />
不漂亮,但對我有用。
static void Main(string[] args)
{
var text = @"
Some contents which is formatted
over multiple
lines but contains a
<pre>
tag which has
also has
multiple line breaks.
</pre>
";
int pre_tag_ini = text.IndexOf("<pre>");
int pre_tag_fim = text.IndexOf("</pre>");
string result = Regex.Replace(text.Substring(0, pre_tag_ini), "\r\n", "<br />");
result += text.Substring(pre_tag_ini, pre_tag_fim - pre_tag_ini);;
result += Regex.Replace(text.Substring(pre_tag_fim, text.Length - pre_tag_fim), "\r\n", "<br />");
Console.Write(result);
Console.ReadLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.