匹配除子模式之外的任何内容

时间:2010-03-11 18:55:58

标签: php regex parsing

我想完成正则表达式尝试做的事情(我认为无效):

<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)搜索。

有一些简单的方法可以做到这一点,我只是错过了吗?

1 个答案:

答案 0 :(得分: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
相关问题