Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NOT a specific word at ending in regex

I have those strings:

"/page/test/myimg.jpg"
"/page/test/"
"/page2/test/"
"/page/test/other"

I want true for all strings starting with /page/test except when it ends with .jpg.

Then I did: /^\/page\/test(.*)(?!jpg)$/. Well, it's not working. :\

It should return like this:

"/page/test/myimg.jpg" // false
"/page/test/" // true
"/page2/test/" // false
"/page/test/other" // true
like image 776
Ratata Tata Avatar asked Sep 20 '25 02:09

Ratata Tata


2 Answers

Use a negative look behind anchored to end:

/^\/page\/test(.*)(?<!\.jpg)$/

For clarity, this regex will match any input that *doesnt end in .jpg:

^.*(?<!\.jpg)$

Edit (now must work in JavaScript too)

JavaScript doesn't support look behinds, so this ugly option must be used, which says that at least one of the last 4 characters must be other than .jpg:

^.*([^.]...|.[^j]..|..[^p].|...[^g])$
like image 146
Bohemian Avatar answered Sep 22 '25 18:09

Bohemian


Easily done with JavaScript:

/^(?!.*\.jpg$)\/page\/test/
like image 43
ridgerunner Avatar answered Sep 22 '25 16:09

ridgerunner