为mongoose URI创建一个正则表达式

时间:2014-08-01 01:14:59

标签: regex mongoose uri

我试图找出如何使用正则表达式验证mongoose URI。我现在的正则表达是:

^(mongodb:\/{2})(\w*?):{0,1}(\w*?)@{0,1}(\w+?):(\d+)\/(\w+?)

我需要能够检测是否输入了用户名和密码,即

mongodb:username:password@localhost:27107/mydatabasename

所以我需要这些案例无效:

mongodb://username:localhost:27107/adfaeadf
mongodb://username:@localhost:27107/adfaeadf
mongodb://:password@localhost:27107/adfaeadf

但这些情况有效:

mongodb://:@localhost:27107/mydatabasename
mongodb://@localhost:27107/mydatabasename
mongodb://localhost:27107/mydatabasename
mongodb:username:password@localhost:27107/mydatabasename

任何帮助将不胜感激

5 个答案:

答案 0 :(得分:1)

^(mongodb:(?:\/{2})?)((\w+?):(\w+?)@|:?@?)(\w+?):(\d+)\/(\w+?)$

http://regex101.com/r/mV2cR7/2了解

对于你的上一个链接,“mongodb:”之后应该有“//”吗?正则表达式将以任何一种方式匹配。

答案 1 :(得分:1)

如果您想支持传递参数:

/^mongodb:\/\/(?:(?:(\w+)?:(\w+)?@)|:?@?)((?:[\w.-])+)(?::(\d+))?(?:\/([\w-]+))?(?:\?([\w-]+=[\w-]+(?:&[\w-]+=[\w-]+)*)?)?$/

答案 2 :(得分:1)

用于 mongodb+srv 用于 mongodb atlas url。

^(mongodb?(\+srv):(?:\/{2})?)((\w+?):(\w+?)@|:?@?)(\w+?):(\d+)\/(\w+?)$

答案 3 :(得分:0)

这与server-a1.host.com格式的服务器(例如,本地主机以外的服务器)或副本集不匹配,请尝试:

^(mongodb:(?:\/{2})?)((\w+?):(\w+?)@|:?@?)(\S+?):(\d+)\/(\S+?)(\?replicaSet=(\S+?))?$

此处的解释:https://regex101.com/r/mV2cR7/47

答案 4 :(得分:0)

如果要在主机上支持多个分片并传递参数:

/^mongodb:\/\/(?:(?:(\w+)?:(\w+)?@)|:?@?)(((?:[\w.-])+)(?::(\d+)),((?:[\w.-])+)(?::(\d+)),((?:[\w.-])+)(?::(\d+)))?(?:\/([\w-]+))?(?:\?([\w-]+=[\w-]+(?:&[\w-]+=[\w-]+)*)?)?$/g