Regular expression: matching only if not ending in particular sequence

前端 未结 2 1371
悲哀的现实
悲哀的现实 2021-01-01 18:41

I would like to test a url that does NOT end in .html

This is the pattern I come up with:

[/\\w\\.-]+[^\\.html$]

T

2条回答
  •  太阳男子
    2021-01-01 19:12

    What engine are you using? If it's one that supports lookahead assertions, you can do the following:

    /((?!\.html$)[/\w.-])+/
    

    If we break it out into the components, it looks like this:

    (            # start a group for the purposes of repeating
     (?!\.html$) # negative lookahead assertion for the pattern /\.html$/
     [/\w.-]     # your own pattern for matching a URL character
    )+           # repeat the group
    

    This means that, for every character, it tests that the pattern /.html$/ can't match here, before it consumes the character.

    You may also want to anchor the entire pattern with ^ at the start and $ at the end to force it to match the entire URL - otherwise it's free to only match a portion of the URL. With this change, it becomes

    /^((?!\.html$)[/\w.-])+$/
    

提交回复
热议问题