我是 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
Run Code Online (Sandbox Code Playgroud)
我在 JavaScript 中尝试过这些:
let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);
Run Code Online (Sandbox Code Playgroud)
但我在这里没有得到版本。
提前致谢。
您可以使用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);Run Code Online (Sandbox Code Playgroud)