正则表达式以相同的字符串开头和结尾,而不仅仅是相同的字符

时间:2018-01-15 11:20:44

标签: javascript regex rex

我想创建一个正则表达式来接收:

<p class="MyClass">
   <p> something 1 </p>
   <p> something 2 </p>
   <span>         <span>  // or more html tag here
   something
</p>
something's here, not in any tag!

从:

<p class="MyClass">
   <p> something 1 </p>
   <p> something 2 </p>
   <span>         <span>  // or more html tag here
   something
</p>
something's here, not in any tag!

<p class="MyClass">
   <p> another thing 1</p>
   <p> another thing 2</p>
   <p> another thing 3</p>
   another thing
</p>
...

我想我会使用正则表达式来匹配<p class="MyClass">和下一个之间的所有内容。所以正则表达式是/(<p class="MyClass">[\s\S]*)<p class="MyClass">/,在这种情况下正常工作。但是当我想要收到此页面的通知http://daotao.dut.udn.vn/sv/G_Thongbao_LopHP.aspx时,它不起作用。 DOM太奇怪了?!

抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

正则表达式应该是

(<p class="MyClass">[\s\S]*?)(?=<p class="MyClass">|$)
  • [\s\S]*?*?是一个惰性量词,因此它匹配最短的默认值为贪婪(匹配最大值)。
  • (?=<p class="MyClass">|$):lookhead以便它不属于匹配项,|$也可以获得最后一场比赛
相关问题