【问题标题】:HTML parsing by regular expression [duplicate]通过正则表达式解析 HTML [重复]
【发布时间】:2016-06-15 00:05:28
【问题描述】:

在我的项目中,我有一个表格。请看下面:

在这里,我有两个字段,HTMl 和 CSS。用户可以通过保存此表单来保存他们的模板。目前,我将 HTML 和 css 作为单独的字段保存在我的数据库中。我需要准备一个包含有效数据的模板。所以,我从数据库中获取 HTML。请参阅以下问题: *** 当我获取 HTML 时。这是一个字符串。

  1. 我需要使用正则表达式从 #{item(1, 5)} 中捕获两个数字(1 和 5)。模式是什么?

  2. 我需要使用正则表达式捕获<div class="layout">....</div> 块。模式是什么?

  3. 我需要使用正则表达式将#{url} 替换为有效数据。模式是什么?

这是带有自定义标签的 HTML:

#{if(total,0)}#{else}
<div id="recommend">
  <div class="title"><p>Title</p></div>
    #{item(1,5)}
  <div class="layout">
    <div class="item">
      <a href="#{url}"><img border="0" alt="#{name}" src="#{image}"></a>
    </div>
    <div class="goods">
       <a href="#{url}">#{truncate(name,27)}</a>
    </div>
    <div class="price">#{comma(price_tax)}</div>
  </div>
  #{/item}
  <br clear="all">
</div>
#{/if}

请帮帮我。

【问题讨论】:

标签: html regex parsing


【解决方案1】:
  1. #{[\w]+\((\d+),(\d+)\)}

https://regex101.com/r/vS0uJ2/1

输出:

MATCH 1  
1.  [94-95] `1`  
2.  [96-97] `5`  
  1. &lt;div class="layout"\&gt;((?:.*?(?:&lt;div).*?(?:&lt;\/div&gt;).*?){0,})&lt;\/div&gt;

https://regex101.com/r/bL8gY3/2

输出:

MATCH 1
1.  [102-371]   
`<div class="layout">
    <div class="item">
      <a href="#{url}"><img border="0" alt="#{name}" src="#{image}"></a>
    </div>
    <div class="goods">
       <a href="#{url}">#{truncate(name,27)}</a>
    </div>
    <div class="price">#{comma(price_tax)}</div>
  </div>`
  1. &lt;a href="(#\{url\})

https://regex101.com/r/aB2sH1/1

输出:

MATCH 1
1.  [161-167]   `#{url}`
MATCH 2
1.  [270-276]   `#{url}`

【讨论】:

  • 关于Q2的答案,我已经检查了你的链接。它可以工作,但是当我在我的代码中使用它时,它不起作用。其他答案正在起作用。
  • 你能告诉我,如果我想捕捉#{image}和#{name},模式会是什么?
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多