我是 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/