营销型网站建设汽车,成都设计公司地址,方案图网站,37网页游戏平台官网普通分组 使用圆括号 () 来创建分组捕获匹配的内容#xff0c;通过正则表达式匹配结果的数组来访问这些捕获的内容。
const str Hello, World!;
const regex /(Hello), (World)!$/;
const match str.match(regex);if (match) {console.log(完整匹配结果… 普通分组 使用圆括号 () 来创建分组捕获匹配的内容通过正则表达式匹配结果的数组来访问这些捕获的内容。
const str Hello, World!;
const regex /(Hello), (World)!$/;
const match str.match(regex);if (match) {console.log(完整匹配结果: , match[0]); console.log(第一个分组结果: , match[1]); console.log(第二个分组结果: , match[2]);
}命名分组 用 ?分组名称 来给分组命名具体用法如下
const str 2024-10-01;
const regex /(?year\d{4})-(?month\d{2})-(?day\d{2})/;
const match str.match(regex);if (match) {console.log(年份: , match.groups.year); console.log(月份: , match.groups.month); console.log(日期: , match.groups.day);
}反向引用 在正则表达式内部或替换字符串中使用 \nn 是分组的编号来引用之前捕获的分组内容。
const str abab;
const regex /(ab)\1/;
const match str.match(regex);if (match) {console.log(完整匹配结果: , match[0]); // ababconsole.log(第一个分组结果(仅一个分组): , match[1]); // ab
}在替换字符串中使用反向引用
const str John Smith;
const regex /(\w) (\w)/;
const newStr str.replace(regex, $2, $1);console.log(替换后的字符串: , newStr); // Smith, John