Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that matches anything not ending in .json

For a web app I'm trying to come up with a javascript regex that matches anything not ending in .json. Sounds simple but I'm finding it pretty damn hard.

I first wanted to do it like this: ^.*(?!\.json$), but that obviously didn't work as it simply matches the entire string. Then I tried ^[^\.]*(?!\.json$) but that matches ab in abc.json.

I've come so far as to come up with two regexes that do the job, but I want to have one regex 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 test them.

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

like image 668
The Fonz Avatar asked Feb 23 '14 00:02

The Fonz


1 Answers

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

/^(?!.*\.json$).*$/.test("foo.json")
false
/^(?!.*\.json$).*$/.test("foo")
true
/^(?!.*\.json$).*$/.test("foo.html")
true
like image 196
Collin Grady Avatar answered Sep 28 '22 19:09

Collin Grady