要捕获正则模式后的字符串,可以使用括号将要捕获的部分括起来,并在正则表达式末尾使用.match()方法或.exec()方法来获取匹配结果。
下面是一个示例代码,演示如何使用正则表达式来捕获匹配结果:
const str = 'Hello, 2022!';
const regex = /(\d+)/; // 匹配连续的数字
// 使用.match()方法获取匹配结果
const matchResult = str.match(regex);
if (matchResult) {
const capturedString = matchResult[0]; // 捕获的正则模式后的字符串
console.log(capturedString); // 输出: 2022
}
// 使用.exec()方法获取匹配结果
const execResult = regex.exec(str);
if (execResult) {
const capturedString = execResult[0]; // 捕获的正则模式后的字符串
console.log(capturedString); // 输出: 2022
}
在上述示例中,我们使用正则表达式/(\d+)/
来匹配连续的数字。使用.match()方法或.exec()方法获取匹配结果,并通过索引[0]
来访问捕获的正则模式后的字符串。在这个例子中,捕获的字符串是"2022"。