为mongoose URI创建正则表达式

nsc4cvqm  于 2023-01-17  发布在  Go
关注(0)|答案(7)|浏览(158)

我正在尝试弄清楚如何用正则表达式验证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

任何帮助都将不胜感激

ehxuflar

ehxuflar1#

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

http://regex101.com/r/mV2cR7/2以获取说明
对于你的最后一个链接,在“mongodb:“后面应该有“//”吗?但是正则表达式会匹配它。

e4yzc0pl

e4yzc0pl2#

如果要支持传递参数:

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

vfh0ocws3#

这将不匹配格式为server-a1.host.com的服务器(例如除localhosts之外)或副本集,请尝试:
^(mongodb:(?:\/{2})?)((\w+?):(\w+?)@|:?@?)(\S+?):(\d+)\/(\S+?)(\?replicaSet=(\S+?))?$
解释如下:https://regex101.com/r/mV2cR7/47

wljmcqd8

wljmcqd84#

+srv for mongodbMap集网址。

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

fykwrbwg5#

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

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

gwo2fgha6#

我的具有命名分组的版本:

/mongodb:\/\/(?:(?<login>[^\:\/\?\#\[\]\@]+)(?::(?<password>[^\:\/\?\#\[\]\@]+))?@)?(?<host>[\w\.\-]+(?::\d+)?(?:,[\w\.\-]+(?::\d+)?)*)(?:\/(?<dbname>[\w\.\-]+))?(?:\?(?<query>[\w\.\-]+=[\w\.\-]+(?:&[\w\.\-]+=[\w.\-]+)*))?/gm

测试地点:https://regex101.com/r/34kvZw/1

8zzbczxx

8zzbczxx7#

这一个为我的情况工作。为mongodbMap集uri

mongodb?(\+srv):\/\/(?:(?<login>[^\:\/\?\#\[\]\@]+)(?::(?<password>[^\:\/\?\#\[\]\@]+))?@)?(?<host>[\w\.\-]+(?::\d+)?(?:,[\w\.\-]+(?::\d+)?)*)(?:\/(?<dbname>[\w\.\-]+))?(?:\?(?<query>[\w\.\-]+=[\w\.\-]+(?:&[\w\.\-]+=[\w.\-]+)*))?

相关问题