V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
huangsong
V2EX  ›  问与答

求助 js 正则移除多余的 html 标签嵌套。

  •  
  •   huangsong · 2020-11-22 14:30:03 +08:00 · 986 次点击
    这是一个创建于 1244 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正则小白,目前在做数据采集解析,发现回来的数据中包含了很多嵌套的标签,例如:

    <div>
    <article> 
     <article> 
      <article> 
       <article> 
        <article> 
         <div> 
          <article> 
           <article> 
            确保各项部署要求落实落地。 
            <br> 报告会在市里设场收听收看。 
           </article> 
          </article> 
         </div> 
        </article> 
       </article> 
      </article> 
     </article> 
    </article> 
    <span data-index="183" data-textnode-index="2" data-raw-text="">编辑</span>
    </div>
    

    希望能通过正则处理掉多余的嵌套标签,得到合理的格式,如:

    <div>
    <article> 
            确保各项部署要求落实落地。 
            <br> 报告会在市里设场收听收看。 
    </article>
    <span data-index="183" data-textnode-index="2" data-raw-text="">编辑</span>
    </div>
    

    求一个正则。

    3 条回复    2020-11-23 10:15:38 +08:00
    ysc3839
        1
    ysc3839  
       2020-11-22 14:38:14 +08:00 via Android
    搜索 <article>\s*<article>,替换为 <article>
    </article> 同理。
    muzuiget
        2
    muzuiget  
       2020-11-22 20:55:09 +08:00
    正则处理不了这种情况的,连匹配嵌套开闭括号都不行,所以老实用 DOM 操作库。
    assilzm
        3
    assilzm  
       2020-11-23 10:15:38 +08:00
    嵌套处理需要平衡,目前.net 和 php 可以办到 其他语言基本上都不行 老实用 dom 解析吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3000 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:08 · PVG 19:08 · LAX 04:08 · JFK 07:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.