javascript - 在 JS 中分离正则表达式
问题描述
const url = "./index.js mongodb://localhost:27017/docs find betty";
docs
是我的数据库名称
const db_name = ?
const url = ?
如何在一个变量中使用正则表达式分离出数据库名称,而在另一个变量中使用 url?
非常感谢任何帮助。
解决方案
使用组匹配来定义要捕获的字符:
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);
推荐阅读
- javascript - 如何在 vue.js 的模板中获取 body html 元素?
- python - 如何链接在两个列表之间创建连接?
- computer-vision - 图像嵌入稀疏性
- java - 在 0mq 套接字上运行的 java 计时器线程的可能替代方案
- javascript - 使用 map、reduce、filter 为 JavaScript 优化嵌套循环
- python - {“title”:“不支持的媒体类型”,无论我尝试什么都会出错:I(
- hierarchical-clustering - 如何从 HDBSCAN 中的 condensed_tree pandas 输出中获取选定的集群?
- statistics - 时间序列数据的收益递减
- java - 如何处理 Android webview 中的“mailto:”和“tel:”链接
- ios - 通过共享扩展从另一个应用程序打开我的应用程序