我喜欢匹配类为“zot”且至少包含两个元素“td”的元素“table”。 一张 table ,例如不应匹配仅包含“th”但不包含“td”的内容。
我尝试了以下表达式但没有成功:
<table class="zot">([\S\s]*?(?!\/table>)<td){2,}
以更易读的自由间距语法表示的相同表达式:
<table class="zot"> # literal
( # begin of group
[\S\s] # non whitespace or whitespace
* # quantifier
? # greediness modificator
(?!\/table>) # negative look ahead assertion with the literal "/table>"
<td # literal
) # end of group
{2,} # quantifier
可能我对负前瞻的理解是错误的。
我为案例创建了一支代码笔:https://regexr.com/43mmh
请问我的错误是什么?谢谢。
下面是我测试的 HTML 代码(与代码笔中的相同):
<table class="zot">
<tr>
<th>a</th>
<th>b</th>
</tr>
<tr>
<td>c</td>
<td>d</td>
</tr>
</table>
<p>Lorem</p>
<table class="zot">
<tr>
<th>e</th>
</tr>
<tr>
<td>f</td>
</tr>
</table>
<table class="zot">
<tr>
<th>g</th>
<th>h</th>
</tr>
<tr>
<td>i</td>
<td>j</td>
</tr>
</table>
我希望有哪些比赛?
<table class="zot">
<tr>
<th>a</th>
<th>b</th>
</tr>
<tr>
<td>c</td>
<td
和
<table class="zot">
<tr>
<th>g</th>
<th>h</th>
</tr>
<tr>
<td>i</td>
<td
最佳答案
假设您希望 foo
出现在 bar
之前,您可以使用
<table class="zot">((?!\/table>).)+foo(?1)+bar(?1)+<\/table>
大意是重复/table>
中/
以外的任意字符,匹配foo
,重复之前的模式再次匹配bar
,再次匹配之前的模式,最后匹配结束表标签。
注意 s
标志和 (?1)
语法的使用,这使得正则表达式更容易阅读。否则,您将不得不使用 [\s\S]
而不是 .
,并手动键入第一个子模式而不是 (?1)
例如
<table class="zot">(?:(?!\/table>)[\s\S])+foo(?:(?!\/table>)[\s\S])+bar(?:(?!\/table>)[\s\S])+<\/table>
也就是说,如果可能的话,无论您使用什么环境,使用适当的 HTML 解析器可能会更优雅。
关于html - RegEx 和 HTML : How to match an element "foo", 其中至少包含两个其他元素 "bar"? (否定前瞻断言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466372/