簡體   English   中英

嵌套標簽的正則表達式(最內層使其更容易)

[英]Regular expression for nested tags (innermost to make it easier)

我對此進行了相當多的研究,但找不到如何將嵌套的 html 標簽屬性匹配的工作示例。 我知道可以在沒有屬性的情況下匹配平衡/嵌套的最內層標簽(例如,正則表達式 for and 將是#<div\\b[^>]*>(?:(?> [^<]+ ) |<(?!div\\b[^>]*>))*?</div> #x)

但是,我希望看到一個正則表達式模式,它可以找到一個帶有屬性的 html 標簽對。

示例:它基本上應該匹配

<div class="aaa"> **<div class="aaa">** <div> <div> </div> **</div>** </div>

並不是

<div class="aaa"> **<div class="aaa">** <div> <div> **</div>** </div> </div>

有人有一些想法嗎?

出於測試目的,我們可以使用: http : //www.lumadis.be/regex/test_regex.php


附注。 史蒂文在他的博客中提到了一個解決方案(實際上是在評論中),但它不起作用

http://blog.stevenlevithan.com/archives/match-innermost-html-element

$regex = '/<div\b[^>]+?\bid\s*=\s*"MyID"[^>]*>(?:((?:[^<]++|<(?!\/?div\b[^>]*>))+)|(<div\b[^>]*>(?>(?1)|(?2))*<\/div>))?<\/div>/i';

RegEx 匹配除 XHTML 自包含標簽之外的開放標簽

事實上,這是絕對不可能的。 HTML 有一些獨特的、神奇的東西,它不受 RegEx 的影響。

匹配最里面匹配的<div></div>標簽對,以及它們的屬性和內容:

#<div(?:(?!(<div|</div>)).)*</div>#s

這里的關鍵是(?:(?!STRING).)*是字符串,因為[^CHAR]*是字符。

信用: https : //stackoverflow.com/a/6996274


PHP 中的示例:

<?php

$text = <<<'EOD'
<div id="1">
  in 1
  <div id="2">
    in 2
    <div id="3">
      in 3
    </div>
  </div>
</div>
<div id="4">
  in 4
  <div id="5">
    in 5
  </div>
</div>
EOD;

$matches = array();
preg_match_all('#<div(?:(?!(<div|</div>)).)*</div>#s', $text, $matches);

foreach ($matches[0] as $index => $match) {
  echo "************" . "\n" . $match . "\n";
}

輸出:

************
<div id="3">
      in 3
    </div>
************
<div id="5">
    in 5
  </div>

我構建了一個簡短的 python 腳本來解決管理嵌套標簽的問題。 它與 html 和其他可怕的嵌套語法一起愉快地運行,就像 wiki 代碼一樣。 Hyrically,我寫它是為了避免正則表達式! 我根本無法理解他們。 :-(。我用這個函數做任何事情,它對 html 和 xml 運行得很好。它也很快,因為它只使用基本的字符串搜索。我很高興知道正則表達式無濟於事。:-)

如果你們中有人感興趣,我想分享腳本; 但是考慮一下,我不是程序員,我認為這個問題已經解決了很長時間!

你可以在我的討論頁找到我。來源: http ://it.wikisource.org/wiki/Discussioni_utente:Alex_brollo

您可以遞歸地執行此操作,使用相同的正則表達式但在需要時執行。 像這樣:

function htmlToPlainText(html) {
    let text = html || ''

    // as there is html nested inside some html attributes, we need a recursive strategy to clean up the html
    while (text !== (text = text.replace(/<[^<>]*>/g, '')));

    return text
  }

這適用於以下情況:

<p data-attr="<span>Oh!</span>">Lorem Ipsum</p>

我在這里找到了這個腳本: http : //blog.stevenlevithan.com/archives/reverse-recursive-pattern

暫無
暫無

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

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