首页 > 解决方案 > 正则表达式:可以在正则表达式中进行子匹配吗?

问题描述

我创建了这个正则表达式来解析 mongodb url,如下所示:

/mongodb://((?'username'\w+):(?'password'\w+)@)?(?'hosts'\w[,\w]*)(/(?'defaultdb'[\w .]+))?(\?(?'options'.*$))?$/m

我用它在regex101中进行了一些测试,我想知道是否可以解析主机组中的“,”(逗号)以生成一个数组,并且类似地在选项组中使用“&”分隔符执行此操作。

我的意图是通过正则表达式结果进行迭代,并以一种方式将匹配组与您的结果一起使用,而无需按分隔符进行拆分。

预期示例:

mongodb://user:password@host,host2,host3,host4/databasename?options=1&options=2

组用户:用户

组密码:密码

组主机:主机

组主机:host2

组主机:host3

组主机:host4

组 defaultdb:数据库名称

组选项:选项=1

组选项:选项=2

标签: regexparsingregex-group

解决方案


一种可能的解决方法是让所有数据按正确的顺序排列:

let str = 'mongodb://user:password@host,host2,host3,host4/databasename?options=1&options=2'
// substring(10) to avoid 'mongodb://'
console.log(str.substring(10).split(/[:@,/&?]/))


编辑:我在您的编辑之前看到您在 Node 上,所以另一个解决方案是:

let str = 'mongodb://user:password@host,host2,host3,host4/databasename?options=1&options=2'

let regex = /mongodb:\/\/(?<username>\w+):(?<password>\w+)@(?<hosts>[,\w]*)\/(?<defaultdb>[\w\.]+)?\?(?<options>.*$)?$/

function splitGroup(group, items)
{
  items.forEach(function (item, index) {
    res.groups[group+'_'+index] = item
  });
}

res = regex.exec(str)

res.groups.hosts = res.groups.hosts.split(',')
res.groups.options = res.groups.options.split('&')

splitGroup('host', res.groups.hosts)
splitGroup('option', res.groups.options)

delete res.groups.hosts
delete res.groups.options

console.log(Object.keys(res.groups).filter(v => v.startsWith('host')))
// [ 'host_0', 'host_1', 'host_2', 'host_3' ]
console.log(Object.keys(res.groups).filter(v => v.startsWith('option')))
// [ 'option_0', 'option_1' ]

推荐阅读