正则表达式匹配内容具有特定文本的标签之间的内容

时间:2014-10-24 16:57:16

标签: regex tags

草堆:

<test 00>
    Don't match
</test>
asdasdasdasdasdasdasda
asdasdasdasdasdasdasda
<test 01>
    Don't match
</test>
asdasdasdasdasdasdasda
asdasdasdasdasdasdasda
<test 10>
    MATCH ME
</test>
asdasdasdasdasdasdasda
asdasdasdasdasdasdasda
<test 11>
    Don't match
</test>

目标:我正在尝试匹配

<test 10>
    MATCH ME
</test>

我最终使用的正则表达式是<test[^>]*?>(.|\n)+?MATCH ME(.|\n)+?</test>。我的问题是我的表达式返回以下

<test 00>
    Don't match
</test>
asdasdasdasdasdasdasda
asdasdasdasdasdasdasda
<test 01>
    Don't match
</test>
asdasdasdasdasdasdasda
asdasdasdasdasdasdasda
<test 10>
    MATCH ME
</test>

1 个答案:

答案 0 :(得分:1)

使用negative lookahead

<test[^>]*>(?:(?!<test[^>]*>)[\S\s])*MATCH ME(.|\n)+?<\/test>

DEMO

使用否定前瞻以及DOTALL修饰符(?s)

(?s)<test[^>]*>(?:(?!<test[^>]*>).)*?MATCH ME.+?<\/test>

DEMO