简体   繁体   English

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

[英]Extract substring from a string using regex in javascript

I am new to javascript, How to extract substring that matches a regex in a string in javascript?我是 javascript 的新手,如何提取与 javascript 中的字符串中的正则表达式匹配的 substring?

For example in python:例如在 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

I tried these in javascript:我在 javascript 中尝试了这些:

let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);

but I am not getting the version here.但我在这里没有得到版本。

Thanks in advance.提前致谢。

You can use RegExp.prototype.exec which returns an Array with the full match and the capturing groups matches:您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM