【问题标题】:Match Anything Except a Sub-pattern匹配除子模式之外的任何内容
【发布时间】:2010-03-11 18:55:58
【问题描述】:

我想完成这个(我相信无效)正则表达式试图做的事情:

<p><a>([^(<\/a>)]+?)<\/a></p>uniquestring

基本上匹配除结束锚标记之外的任何内容。简单的非贪婪在这里没有帮助,因为 `uniquestring' 很可能在另一个遥远的结束锚标记之后:

<p><a>text I don't <tag>want</tag> to match</a></p>random 
data<p><a>text I do <tag>want to</tag> match</a></p>uniquestring more
matches <p><a>of <tag>text I do</tag> want to match</a></p>uniquestring 

所以我在锚标签之间有更多标签。我正在使用uniquestring 的存在来确定我是否要匹配数据。因此,一个简单的非贪婪最终匹配了从我不想要的数据的开头到我想要的数据的结尾的所有内容。

我知道我正在接近正则表达式(或至少我对它们的了解)不擅长解决的问题。我可以通过 HTML/XML 解析器中的数据,但这只是一个简单的(ish)搜索。

是否有一些我只是想念的简单方法来做到这一点?

【问题讨论】:

    标签: php regex parsing


    【解决方案1】:

    您正在寻找零宽度负后视:

    <p><a>((?<!<\/a>).)+<\/a><\/p>uniquestring
    

    测试:

    (zyx:~) % echo $T
    <p><a>text I don't <tag>want</tag> to match</a></p>random  data<p><a>text I do <tag>want to</tag> match</a></p>uniquestring more matches <p><a>of <tag>text I do</tag> want to match</a></p>uniquestring
    (zyx:~) % echo $T | grep -oP '<p><a>((?<!<\/a>).)+<\/a><\/p>uniquestring'
    <p><a>text I do <tag>want to</tag> match</a></p>uniquestring
    <p><a>of <tag>text I do</tag> want to match</a></p>uniquestring
    

    【讨论】:

    • 确实是我想要的!我几乎明白了。 :-)
    • 我会使用 lookahead,而不是lookbehind。按照您的方式,它必须一直通过&lt;/a&gt; 序列,然后才能意识到它不应该匹配它。 (?!&lt;\/a&gt;) 在第一个字符处停止匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2015-05-30
    • 2014-01-30
    • 2021-05-26
    相关资源
    最近更新 更多