javascript - 在javascript中使用正则表达式从字符串中提取子字符串
问题描述
我是 javascript 新手,如何在 javascript 中提取与字符串中的正则表达式匹配的子字符串?
例如在 python 中:
version_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
line = "[2021-05-29] Version 2.24.9"
found = version_regex.search(line)
if found:
found.group() // It will give the substring that macth with regex in this case 2.24.9
我在javascript中尝试了这些:
let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);
但我没有在这里得到版本。
提前致谢。
解决方案
您可以使用RegExp.prototype.exec
which 返回Array
具有完全匹配和捕获组匹配的 an:
const input = '[2021-05-29] Version 2.24.9';
const regex = /(\d+)\.(\d+)\.(\d+)/;
let x = regex.exec(input);
console.log(x);
推荐阅读
- bash - 如何使用 bash 将基于标识符的多个文件合并到一个大矩阵中?
- xamarin - Xamarin Windows 无法访问指定的设备、路径或文件
- go - 遍历 struct na Go 的第 N 个字段
- django - 'NoneType' 对象对于序列化程序不可迭代
- python - 在 python 的命令提示符下安装 sklearn 时遇到问题,出现 ERROR: Command errored out with exit status 1:
- java - 从 springfox2 迁移到 springfox 3.0
- c++ - Cmake 在另一个自定义库中包含一个自定义库
- python - 如何从 Django 3 中的 URL 中捕获数值?
- jquery - jQuery - 使用自动完成和 -internal-input-suggested 输入自动宽度
- git - 将 kubeflow 管道文件与 git 同步