Regex that matches any that doesn't end in .json

For a web application, I am trying to come up with a javascript regex that matches anything not ending in .json. It sounds easy, but I find it pretty damn complicated.

At first, I wanted to do it this way: ^.*(?!\.json$)but it clearly didn't work, as it just matches the whole line. Then I tried ^[^\.]*(?!\.json$), but matches abin abc.json.

I went so far as to come up with two regular expressions that do the job, but I want to have one regular expression that can do this.

// Match anything that has a dot but does not end in .json
^.*\.(?!json$)
// Match anything that doesn't have a dot
^[^\.]*$

I like http://regex101.com/#javascript to check them out.

I am using regexp as part of ExpressJS's route definition app.get(REGEXP, routes.index).

+3
source share
4 answers

Try /^(?!.*\.json$).*$/

/^(?!.*\.json$).*$/.test("foo.json")
false
/^(?!.*\.json$).*$/.test("foo")
true
/^(?!.*\.json$).*$/.test("foo.html")
true
+5
source

You can always just get the file extension and then compare it.

Regex to search for file extension

/\.[^.]*$/

get file extension using

var extension = /\.[^.]*$/.exec("something.json");

if(extension[0] === ".json"){
    //do something
}
+1
source

, "match (not.json)" " (.json)", ?

0

.json, , ,

match == false

, , , .

0

All Articles