簡體   English   中英

使用正則表達式替換兩個字符串之間的字符,同時忽略html標記和換行符

[英]Using regex to replace characters between two strings while ignoring html tags and new line breaks

我需要通過用█替換字符來刪除已加載到字符串變量中的電子郵件中的健康信息。 有問題的電子郵件需要在“健康問題?”之間添加內容。 和“您工作了嗎”替換了,但忽略了標簽中出現的所有內容。 另外,行通常用=符號包裹,這些新行,空格和=符號可以出現在標簽的中間,也可以出現在用於標識開始和結束的字符串的中間。

例:

(More content)
.....have any health issues? We currently do not have any health issues</sp=
an></li>
 <li id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439_17326" styl=
e=3D"margin-top:0;margin-bottom:0;vertical-align:middle;line-height:15pt;co=
lor:black"><span id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439=
_17327" style=3D"font-family:Arial;font-size:11.0pt">Some more text. 
Have
     you worked.....(more content)

我想有一種方法可以使用一個或多個正則表達式在javascript中執行此操作,但我不知所措。

所需的結果如下所示:

(More content)
.....have any health issues?███████████████████████████████████████████</sp=
an></li>
 <li id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439_17326" styl=
e=3D"margin-top:0;margin-bottom:0;vertical-align:middle;line-height:15pt;co=
lor:black"><span id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439=
_17327" style=3D"font-family:Arial;font-size:11.0pt">███████████████
Have
     you worked.....(more content)

您可以使用兩種replace方法來解決此問題。 第一個匹配health issues?中的所有事物health issues? Have you worked分成三個捕獲組。 我們對第二捕獲小組感興趣:

(health issues\?)([\s\S]*?)(Have\s+you\s+worked)
                  ^^^^^^^^

我們在捕獲的組上運行第二個replace方法,並用替換標簽之外的每個字符。 這是正則表達式:

(<\/?\w[^<>]*>)|[\s\S]

我們需要保留第一個捕獲組(它們可能是HTML標記),並用提到的字符替換另一邊( [\\s\\S] )。

免責聲明:這不是防彈,因為正則表達式不應該用於解析HTML標簽。

演示:

 var str = `(More content) .....have any health issues? We currently do not have any health issues</sp= an></li> <li id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439_17326" styl= e=3D"margin-top:0;margin-bottom:0;vertical-align:middle;line-height:15pt;co= lor:black"><span id=3D"m_-622133557606915713yui_3_16_0_ym19_1_1515713539439= _17327" style=3D"font-family:Arial;font-size:11.0pt">Some more text. Have you worked.....(more content)`; console.log(str.replace(/(health issues\\?)([\\s\\S]*?)(Have\\s+you\\s+worked)/, function(match, $1, $2, $3) { return $1 + $2.replace(/(<\\/?\\w[^<>]*>)|[\\s\\S]/g, function(match, $1) { return $1 ? $1 : '█'; }) + $3; })); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM