Stop at first character match?

This question already has an answer here:

  • Greedy vs. Reluctant vs. Possessive Quantifiers 7 answers

  • + is a greedy operator meaning it matches as much as it possibly can and still allows the rest of the regex to match. For this, I recommend using a negated class meaning any character except: " "one or more" times.

    /<a href="ftp:([^"]+)">/
    

    Live Demo


    Make your regex ungreedy:

    /<a href="ftp:(.+?)">/
    //        here __^
    

    or:

    /<a href="ftp:([^>"]+)">/
    

    But it's better to use a parser.


    * , + are greey (matches as much as possible). By appending ? after them, you can make non-greedy.

    /<a href="ftp:(.+?)">/
    

    or you can specify exclude " using negated character classes ( [^...] ):

    /<a href="ftp:([^"]+)">/
    

    BTW, it's not a good idea to use regular expression to parse HTML.

    链接地址: http://www.djcxy.com/p/76900.html

    上一篇: 为什么这个正则表达式模式不匹配?

    下一篇: 在第一个字符比赛停止?