【问题标题】:JS RegExp Start at the second occurrence of <h2> tag and include everything after itJS RegExp 从 <h2> 标记的第二次出现开始并包含它之后的所有内容
【发布时间】:2019-08-08 14:08:44
【问题描述】:

使用正则表达式 (Javascript) 我需要在文章中找到第二个 &lt;h2&gt; 标记并返回它之后的所有内容,包括第二个 &lt;h2&gt; 标记。

我有一篇文章需要分成三个部分。我已经有了前两部分,文章的第三部分就是我上面描述的。

“标记”是开头的&lt;h2&gt; 标签,这意味着我文章的第一部分从字符串的最开头开始,并在第一个&lt;h2&gt; 标签之前停止,不包括它。

第二部分包括第一个 &lt;h2&gt; 标记并包括它之后的所有内容,就在第二个 &lt;h2&gt; 标记之前。

现在我需要一个正则表达式,它可以找到第二个 &lt;h2&gt; 标记,包括该标记及其之后的所有内容,直到字符串结尾。

这是我目前所得到的:

文章结构:

<p>Here's the first paragraph</p>
<p>Here's the second one</p>
<p>Here's the third one</p>
<a>A link maybe</a>

<h2>Here's the first H2 tag</h2>
<p>Another paragraph</p>
<a>A link maybe</a>
<img An image/>
<p>Another paragraph</p>

<h2>Here's the second H2 tag</h2>
<p>Another paragraph</p>
<a>A link maybe</a>
<img An image/>
<p>Another paragraph</p>

返回前三个&lt;p&gt;&lt;/p&gt;s 和&lt;a&gt;&lt;/a&gt; 并排除第一个&lt;h2&gt; 的正则表达式是:

const firstBreak = /.+?(?=\<h2>)/im;
this.articleBody.match(firstBreak)[0]

第二个正则表达式返回第一个 &lt;h2&gt; 及其之后的所有内容,直到第二个 &lt;h2&gt;,不包括第二个 &lt;h2&gt;

const secondBreak = /.+?(?=\<h2>)/gim;
this.articleBodyMiddle = this.articleBody.match(secondBreak)[1];

第三个正则表达式是我难住的地方。这个包括第一个&lt;h2&gt;,它之后的所有内容和第二个&lt;h2&gt; 以及它之后的所有内容:

const thirdBreak = /(\<h2>?.*)/gi;
this.articleBodyBottom = this.articleBody.match(thirdBreak)[0];

我只需要最后一个从第二个 &lt;h2&gt; 开始并包含它之后的所有内容。

感谢您的帮助!

【问题讨论】:

  • 使用正则表达式来解析 XML/HTML 几乎不能很好地工作......这不是正则表达式的设计目的。您可能会考虑使用browser's built-in DOMParser,然后使用 xpath 或 querySelectorAll 或其他东西获得您想要的。
  • 嗨@David784,感谢您的评论。我知道这是我实际上需要将该内容插入不同的divs 并在它们之间另外插入组件的少数情况之一。

标签: javascript regex string tags


【解决方案1】:

也许会有所帮助:

var str = `<p>Here's the first paragraph</p>
<p>Here's the second one</p>
<p>Here's the third one</p>
<a>A link maybe</a>

<h2>Here's the first H2 tag</h2>
<p>Another paragraph</p>
<a>A link maybe</a>
<img An image/>
<p>Another paragraph</p>

<h2>Here's the second H2 tag</h2>
<p>Another paragraph</p>
<a>A link maybe</a>
<img An image/>
<p>Another paragraph</p>`;

var result = str.match(/^[^]*?<h2>[^]*?(<h2>[^]*?)$/);
console.log(result[1]);

解释:

  • ^ 字符串的开头。
  • [^]*?&lt;h2&gt; 匹配任何东西直到第一个 &lt;h2&gt;
  • 第二个[^]*? 匹配第一个和第二个&lt;h2&gt; 之间的任何内容
  • (&lt;h2&gt;[^]*?)$ 捕获第二个 &lt;h2&gt; 及其之后的所有内容。

【讨论】:

  • @Cuong Le Ngoc 非常感谢!这就像一个魅力!我真的被难住了。也感谢您的详细解释!
猜你喜欢
  • 2021-01-12
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2014-10-19
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
相关资源
最近更新 更多