javascript - 在javascript中使用正则表达式从字符串中提取子字符串

标签 javascript regex

我是 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它返回一个包含完整匹配和捕获组匹配的 Array:

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

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

let x = regex.exec(input);

console.log(x);

关于javascript - 在javascript中使用正则表达式从字符串中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68878912/

相关文章:

javascript - 如何在 Javascript 中修改 Array.prototype

javascript - 如何在提交时将每个输入段落包装到单独的输入字段中?

python - 在 Python 中使用正则表达式从字符串中的源代码中提取字符串常量

javascript - 如何强制 node.js 进行更深层次的递归?

javascript - Moment.js 问题用夏令时添加天数

javascript - 在 Windows 10 中使用 NodeJS 在本地运行异步函数

javascript - 分割字符串并保留分号与以下文本

python - 使用正则表达式按 date_format 查找时间戳

javascript - 单个正则表达式匹配范围(1999-2010)还是仅匹配单个值(2010)?

javascript - 使用具有特殊条件的正则表达式(lookahead/lookbehind)字符串替换哈希