对于网络应用程序,我试图提出一个 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/