首页 > 解决方案 > 在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);

但我没有在这里得到版本。

提前致谢。

标签: javascriptregex

解决方案


您可以使用RegExp.prototype.execwhich 返回Array具有完全匹配和捕获组匹配的 an:

const input = '[2021-05-29] Version 2.24.9';

const regex = /(\d+)\.(\d+)\.(\d+)/;

let x = regex.exec(input);

console.log(x);


推荐阅读