regex - 正则表达式:可以在正则表达式中进行子匹配吗?
问题描述
我创建了这个正则表达式来解析 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
解决方案
一种可能的解决方法是让所有数据按正确的顺序排列:
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' ]
推荐阅读
- mysql - 有没有办法使用 SQL 查询将埃及字符作为文本加载到表中?
- input - 如何专注于从 Svelte 中的组件加载的输入字段?
- javascript - 在我生成的每个索引上制作不同的 V-MODEL
- apache-spark - 如何根据分隔符将数据框中的行拆分为多行
- android - 为 Android 应用程序的第三方分析库记录 http 流量网络
- reactjs - 在 mapDispatchToProps 之外的函数中调度动作
- python - 无法在 AWS postgres RDS 中插入数据
- angular - Angular 6 如何将假期添加到剑道 UI 调度程序?
- android - 如何防止Android服务中的代码运行两次
- wso2 - 如何使用 REST API 在 WSO2 中为特定 API 启用 CORS 配置?