html - RegEx 和 HTML : How to match an element "foo", 其中至少包含两个其他元素 "bar"? (否定前瞻断言)

标签 html regex regex-lookarounds

我喜欢匹配类为“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>

https://regexr.com/43nkb

大意是重复/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/

相关文章:

python - 正则表达式匹配whatsapp聊天日志

javascript - 匹配给定的正则表达式,除非给定的单词存在(lookahead 或lookbehind)

Javascript if (j === null) 什么都不做

javascript - 使用ajax获取php返回值

JavaScript 正则表达式 : Ignore anything in between?

regex - 如何使用正则表达式查找和替换字符串的开头和结尾

python - 如何在Python中找到列表中单词最多的句子?

html - 尝试修复 css 和 html 以协同工作

javascript - 小费计算器javascript

javascript - 正则表达式模式只有一个点并匹配整数和小数