javascript - 匹配任何不以 .json 结尾的正则表达式

标签 javascript regex express

对于网络应用程序,我试图提出一个 javascript 正则表达式来匹配任何不以 .json 结尾的内容。听起来很简单,但我发现它非常难。

我首先想这样做:^.*(?!\.json$),但这显然行不通,因为它只是匹配整个字符串。然后我尝试了 ^[^\.]*(?!\.json$) 但匹配 abc.json 中的 ab

到目前为止,我已经提出了两个可以完成这项工作的正则表达式,但我想要一个可以完成这项工作的正则表达式。

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

我喜欢http://regex101.com/#javascript测试它们。

我在 app.get(REGEXP, routes.index) 中使用正则表达式作为 ExpressJS 路由定义的一部分。

最佳答案

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

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

关于javascript - 匹配任何不以 .json 结尾的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21962329/

相关文章:

javascript - 正则表达式和换行减号

Javascript正则表达式难倒了

javascript - 护照发送后无法设置 header

javascript - Mongoose - 子架构引用父子文档

c++ - 如何使用cpp的regex_iterator在第一次匹配时停止

javascript - 如何用JS获取日期?

node.js - Passport.authenticate 导出 -> Passport.authenticate( 一些东西 ) (req, res, next)?

node.js - Express.js : Route Function not called express. js

javascript - 如何在嵌入式样式表中使用 javascript 变量作为背景?

javascript - 哪种方法用 jQuery 查找最近的后代更有效?