代码之家  ›  专栏  ›  技术社区  ›  Tim Lytle

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

  •  2
  • Tim Lytle  · 技术社区  · 14 年前

    我想完成这个(我相信是无效的)正则表达式要做的工作:

    <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 回复  |  直到 14 年前
        1
  •  1
  •   ZyX    14 年前

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

    <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