helloworld12
V2EX  ›  问与答

请教下正则问题

  •  
  •   helloworld12 · Oct 30, 2017 · 1632 views
    This topic created in 3211 days ago, the information mentioned may be changed or developed.

    太久没写了,忘得有点严重

    <span xxx...><a>xxx...</a></span> 
    
    <span xxx...>xxx...</span> 
    

    要怎么匹配上面的字符串?

    以下是我想的正则表达式

    r'<span[^>]*>[^</span>]*</span>'
    

    问题是 [^</span>]* 没有匹配到 <a>xxx...</a>

    现在回头看 前缀匹配,看得有点懵

    谢谢啦

    2 replies    2017-10-31 01:45:48 +08:00
    Rheinmetal
        1
    Rheinmetal  
       Oct 31, 2017 via Android   ❤️ 1
    两个正则分别匹配咯
    [^< /span>] 是不包 7ge 字符 xxxxxxx 里面有 span 这 几个字符 就漏了
    比如你这个 a 就是这样
    <span [^>]*>[^<]*</span>
    <span[^>]*><a>[^<]*</a></span>
    要不就是
    考虑匹配两次 di 一次 span 然后 在结果里面找 a
    为啥不用专门处理这个的 xpath 之类 的工具?
    noqwerty
        2
    noqwerty  
       Oct 31, 2017   ❤️ 1
    所以你到底是只想要字符串还是想要<span>里的所有内容?如果是字符串的话建议 xpath 或者 CSS selector,如果是所有内容的话:
    r'<span[^>]*>(.*)</span>'
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   914 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 22:45 · PVG 06:45 · LAX 15:45 · JFK 18:45
    ♥ Do have faith in what you're doing.