Negative lookahead Regular Expression

前端 未结 7 936
后悔当初
后悔当初 2020-11-27 14:00

I want to match all strings ending in \".htm\" unless it ends in \"foo.htm\". I\'m generally decent with regular expressions, but negative lookaheads have me stumped. Why

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 14:52

    What you are describing (your intention) is a negative look-behind, and Javascript has no support for look-behinds.

    Look-aheads look forward from the character at which they are placed — and you've placed it before the .. So, what you've got is actually saying "anything ending in .htm as long as the first three characters starting at that position (.ht) are not foo" which is always true.

    Usually, the substitute for negative look-behinds is to match more than you need, and extract only the part you actually do need. This is hacky, and depending on your precise situation you can probably come up with something else, but something like this:

    // Checks that the last 3 characters before the dot are not foo:
    /(?!foo).{3}\.htm$/i.test("/foo.htm"); // returns false 
    

提交回复
热议问题