1

I am using the following regex:

https://(dev-|stag-|)(assets|images).server.io/v[\d]/file/(.*?)/(?!(download$))

The intention is to match Url 1 & 3 completely, but not Url 2, but it doesn't seem to work.

By checking the following answers: Javascript regex negative look-behind, Regex: match everything but, I believe a negative lookbehind would work, but am unable to figure out what the regex for that would be.

Any help with it would be greatly appreciated!

iyerrama29
  • 496
  • 5
  • 15

1 Answers1

1

The (?!(download$)) part by itself isn't doing the right thing here since it fails the match if there is download and end of string immediately to the right of the last / matched. You need to actually match the last subpart with a consuming pattern to actually match the filename.

You may use

/https:\/\/(dev-|stag-)?(assets|images)\.server\.io\/v\d\/file\/(.*?)\/(?!download$)[^\/]+$/
                                                                     ^^^^^^^^^^^^^

See the regex demo. If you need to match the whole string, add ^ anchor at the start of the pattern. s may be also made optional with ? after it.

Details

  • https:\/\/ - a https:// substring
  • (dev-|stag-)? - an optional dev- or stag- substring
  • (assets|images) - either assets or images substring
  • \.server\.io\/v - a .server.io/v substring
  • \d - any digit
  • \/file\/ - a /file/ substring
  • (.*?) - any 0+ chars other than line break chars, as few as possible
  • \/ - a /
  • (?!download$) - there must not be a download substring followed with the end of string position immediately to the right of the current location
  • [^\/]+ - 1 or more chars other than /, as many as possible
  • $ - end of string.

Note that [\d] is less readable than \d, and you need to escape . symbols in the pattern if you want to match literal dot chars.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563