簡體   English   中英

無法將文本與正則表達式匹配

[英]Can't match text with regexp

我正在嘗試將以下文本與以下正則表達式匹配,但它不起作用(下面的打字稿代碼):

const s2 = "<div class=\"MsgBlock plain\" "
+"style=\"background: white;padding-left: 8px;min-height: 50px;padding-top: 4px;padding-bottom: 4px;width: 100%;border: none;\">"
+"<font size=\"-1\" color=\"#31a217\" face=\"monospace\">[remote content blocked for your privacy]</font><br /><br />\n\n\n  "
+"Terms of Service</a>\n      </td>\n    </tr>\n  </table></div>"
const m2 = s2.match(/<div class="MsgBlock ([a-z]+)" style="[^"]+">(.*)<\/div>/);
console.log(m2 === null ? "M2: (no match)" : "M2: " + m2.toString())

這將打印出M2: (no match) 當我將正則表達式更改為/<div class="MsgBlock ([az]+)" style="[^"]+">(.*)<\\//它匹配部分文本時,輸出為:

M2: <div class="MsgBlock plain" style="background: white;padding-left: 8px;min-height: 50px;padding-top: 4px;padding-bottom: 4px;width: 100%;border: none;"><font size="-1" color="#31a217" face="monospace">[remote content blocked for your privacy]</,plain,<font size="-1" color="#31a217" face="monospace">[remote content blocked for your privacy]

誰能解釋為什么會發生這種情況以及如何修復正則表達式以匹配此文本? 請注意,正則表達式適用於其他一些文本。

注意:我問的正是我在問什么。 請不要建議使用 HTML 解析器。

我已經使用了您的正則表達式模式並在您的特定情況下對其進行了測試,結果在此正則表達式測試器鏈接上是正確的

正則表達式正在通過測試

所以問題可能出在您的實現中,而不是正則表達式邏輯本身。

我建議使用文字字符串模板而不是像下面這樣連接多個 js 字符串

const s2 = `
<div class="MsgBlock plain" style="background: white;padding-left: 8px;min-height:
50px;padding-top: 4px;padding-bottom: 4px;width: 100%;border: none;">
<font size="-1"
 color="#31a217" face="monospace">
[remote content blocked for your privacy]</,plain,
<font size="-1" color="#31a217" face="monospace">[remote content blocked for your
privacy]</font><br /><br />\n\n\nTerms of Service</a>\n      </td>\n    </tr>\n  </table></div>
`

因為字符串連接可能導致此錯誤

看起來當前正則表達式中的(.*)無法匹配某些空格(例如換行符)。 將其更改為([\\s\\S]+)匹配的示例文本。

那是你想要的嗎?

 const s2 = "<div class=\\"MsgBlock plain\\" " +"style=\\"background: white;padding-left: 8px;min-height: 50px;padding-top: 4px;padding-bottom: 4px;width: 100%;border: none;\\">" +"<font size=\\"-1\\" color=\\"#31a217\\" face=\\"monospace\\">[remote content blocked for your privacy]</font><br /><br />\\n\\n\\n " +"Terms of Service</a>\\n </td>\\n </tr>\\n </table></div>" const [m2,m3,m4] = s2.match(/^<div class="MsgBlock ([\\S]+)"\\s*style="[^"]+">([\\s\\S]*)<\\/div>$/); console.log(m3); console.log(m4);

暫無
暫無

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

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