How to make a regex for files ending in .php?

前端 未结 3 1670
猫巷女王i
猫巷女王i 2020-12-21 15:02

I\'m trying to write a very simple regular expression that matches any file name that doesn\'t end in .php. I came up with the following...

(.*?)(?!\\.php)$         


        
3条回答
  •  渐次进展
    2020-12-21 15:31

    Instead of using negative lookahead, sometimes it's easier to use the negation outside the regex at the hosting language level. In many languages, the boolean complement operator is the unary !.

    So you can write something like this:

    ! str.hasMatch(/\.php$/)
    

    Depending on language, you can also skip regex altogether and use something like (e.g. Java):

    ! str.endsWith(".php")
    

    As for the problem with the original pattern itself:

    (.*?)(?!\.php)$   // original pattern, doesn't work!
    

    This matches, say, file.php, because the (.*?) can capture file.php, and looking ahead, you can't match \.php, but you can match a $, so altogether it's a match! You may want to use look behind, or if it's not supported, you can lookahead at the start of the string.

    ^(?!.*\.php$).*$  // negative lookahead, works
    

    This will match all strings that does not end with ".php" using negative lookahead.

    References

    • regular-expressions.info/Lookarounds

    Related questions

    • How does the regular expression (?<=#)[^#]+(?=#) work?

提交回复
热议问题