首页 > 解决方案 > 在 JS 中分离正则表达式

问题描述

const url = "./index.js mongodb://localhost:27017/docs find betty";

docs是我的数据库名称

const db_name = ? 
const url = ? 

如何在一个变量中使用正则表达式分离出数据库名称,而在另一个变量中使用 url?

非常感谢任何帮助。

标签: javascriptregex

解决方案


使用组匹配来定义要捕获的字符:

const input = "./index.js mongodb://localhost:27017/docs find betty";

const regex = /(mongodb:\/\/\w*(\:\d{1,5})?\/(\w*))/;

const url = input.match(regex)[1];
const db_name = input.match(regex)[3];

console.log(url);
console.log(db_name);


推荐阅读