javascript regex - look behind alternative?

前端 未结 6 1880
时光取名叫无心
时光取名叫无心 2020-11-22 05:44

Here is a regex that works fine in most regex implementations:

(?

This matches .js for a string which ends with .js exc

6条回答
  •  遥遥无期
    2020-11-22 06:32

    EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.

    In previous versions, you can do this:

    ^(?:(?!filename\.js$).)*\.js$
    

    This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.

    ^                 # Start of string
    (?:               # Try to match the following:
     (?!              # First assert that we can't match the following:
      filename\.js    # filename.js 
      $               # and end-of-string
     )                # End of negative lookahead
     .                # Match any character
    )*                # Repeat as needed
    \.js              # Match .js
    $                 # End of string
    

    Another edit:

    It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:

    ^(?!.*filename\.js$).*\.js$
    

    works just as well:

    ^                 # Start of string
    (?!               # Assert that we can't match the following:
     .*               # any string, 
      filename\.js    # followed by filename.js
      $               # and end-of-string
    )                 # End of negative lookahead
    .*                # Match any string
    \.js              # Match .js
    $                 # End of string
    

提交回复
热议问题