[英]A string replace function with support of custom wildcards and escaping these wildcards in C#
[英]replace a string using wildcards
我有一段html代碼,我想要消除一些樣式部分,我知道我需要正則表達式但我不知道如何生成正則表達式甚至如何在我的c#代碼中應用它。 以下是原始字符串的示例:
<p style="color: #000000; text-transform: none; letter-spacing: normal; font-size: 12px; font-style: normal; font-variant: normal; font-weight: normal; word-spacing: 0px; white-space: normal; font-size-adjust: none; font-stretch: normal; -webkit-text-stroke-width: 0px;">
這是我希望在替換操作后獲得的輸出:
<p>
我想擺脫style屬性。 我需要為<p ...>
所有出現做這件事
關於這種工作有很多例子,但我對此感到困惑。 所以解決方案的任何線索都會很棒。 提前致謝。
你真的找到一個正則表達式教程( 例子 )來了解匹配是如何工作的,然后替換會更容易...
string output = Regex.Replace(input, @"(?<=<p)[^>]+", "");
見演示 。
要僅刪除style屬性,您可以使用:
string output = Regex.Replace(input, @"(?<=<p)\s*style=""[^""]+""", "");
請注意,如果style屬性緊跟在<p
(具有任意數量的空格)之后,這將不起作用。
更新的演示 。
要刪除html中任何位置的屬性樣式,您可以使用(比前一個更安全):
string output = Regex.Replace(input, @"(?<=<p)([^>]*?)\s*style=""[^"">]+""", "$1");
重新演示 。
不知道如何在c#中做到這一點,但是在bash正則表達式中使用一般的例子,我會這樣做:
echo "$pattern" | sed -r 's/(<p).*(>)/\1\2/'
哪里:
(<p) ----- Captures the opening bracket with p
.* ----- Anything inbetween up to the next ">"
() ----- Captures the closing bracket
\1\2 ----- Gives you back the two captured things,
in this order, with no space inbetween
希望它有所幫助,但同樣,你需要自己尋找替換c#。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.