最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex that matches anything not ending in .json - Stack Overflow

programmeradmin3浏览0评论

For a web app I'm trying to e 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 e so far as to e 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 to test them.

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

For a web app I'm trying to e 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 e so far as to e 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./#javascript to test them.

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

Share Improve this question edited Feb 23, 2014 at 0:31 user234932 asked Feb 23, 2014 at 0:00 The FonzThe Fonz 951 silver badge6 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 12

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

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

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

Regex to find file extension

/\.[^.]*$/

get the file extension with

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

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

maybe instead of testing "match (not .json)" you could test "not match (.json)", which is easy ?

I would create a regex to match .json and then when you check for it reverse the logic with a

match == false

That would be much simpler and it shows what you are trying to do making it a lot more obvious to other programmers.

发布评论

评论列表(0)

  1. 暂无评论