代码之家  ›  专栏  ›  技术社区  ›  Suresh

具有负前瞻和非贪婪的正则表达式匹配

  •  1
  • Suresh  · 技术社区  · 8 年前

    <html name="abc:///Testers/something.txt" in="abc/Testers/something.txt" loci="123" sap="abcdefgh="/><html name="abc:///needed.txt" src="abc/needed.txt" location="123" sap="rtyghu"/><html name="abc:///Testers/Testers3/Another.txt" in="abc/Testers/Testers3/Another.txt" loci="123" sap="jhkiopjhg"/><html name="abc:///onemore.txt" src="abc/onemore.txt" location="123" sap="dfrtyu"/>
    

    如何匹配从 <html name=" not followed by (needed) or (onemore) and ending with />

    <html name="abc:///Testers/something.txt" in="abc/Testers/something.txt" loci="123" sap="abcdefgh="/>
    <html name="abc:///Testers/Testers3/Another.txt" in="abc/Testers/Testers3/Another.txt" loci="123" sap="jhkiopjhg"/>
    

    <html name=(?!(needed|onemore)).*?"\/>

    它不起作用,因为我对非贪婪和消极的前瞻性东西感到困惑。

    2 回复  |  直到 8 年前
        1
  •  4
  •   revo shanwije    8 年前

    除了对应该放弃遍历的位置进行限制外,还需要使用重复量词:

    <html\s+name="(?![^"]*(?:needed|onemore))[^>]*>
    

    Live demo

        2
  •  2
  •   Tezra    8 年前

    这是你的正则表达式的分解 <html name=(?!(needed|onemore)).*?"\/>

    <html name=(?!(needed|onemore)).*?"\/>
    1) Literal match: <html name=
    2) Not followed by: "needed" or "onemore"
    3) Lazy grab all: .*?
      Until Literal match: "/>
    

    <html name=(?:(?!(needed|onemore)).)*?"\/> 。这将检查每个角色抓取的下一个不是“needed”或“onemore”。(我还建议使用 [^>] .

    不过,我建议您在过滤时使用类似的方法 <html name=([^>no]|n(?!eeded)|o(?!nemore))*> 。regex引擎更容易适应,工作量更少。