JavaScript正则表达式中的(?<>)命名捕获组模式是什么?
JavaScript正则表达式中的
(?<>)模式详解 (?<name>...)是JavaScript正则表达式中的命名捕获组,它给捕获的子匹配内容赋予自定义名称,相比传统数字索引捕获组,可读性更强,后续引用也更直观。
核心作用
传统捕获组(...)会按顺序给捕获内容分配数字索引($1、$2等),命名捕获组通过<name>指定名称,后续可直接通过名称访问捕获结果,避免了索引数字混乱的问题。
示例解析
拿你给出的正则表达式来看:
/^github.com\/(?<root>[\w-]+)\/(?<repo>[\w-]+)\/(?<branch>[\w-]+)$/
这个正则用于匹配github.com/[拥有者]/[仓库名]/[分支名]格式的路径,其中:
(?<root>[\w-]+):捕获第一个斜杠后的拥有者名称,命名为root,匹配内容包含字母、数字、下划线和连字符(?<repo>[\w-]+):捕获第二个斜杠后的仓库名称,命名为repo(?<branch>[\w-]+):捕获第三个斜杠后的分支名称,命名为branch
使用方式
- 通过
exec()获取捕获结果
匹配后返回的结果对象中,groups属性会包含所有命名捕获组的键值对:
const regex = /^github.com\/(?<root>[\w-]+)\/(?<repo>[\w-]+)\/(?<branch>[\w-]+)$/; const matchResult = regex.exec('github.com/octocat/hello-world/main'); console.log(matchResult.groups.root); // 输出 "octocat" console.log(matchResult.groups.repo); // 输出 "hello-world" console.log(matchResult.groups.branch); // 输出 "main"
- 正则内部反向引用
在正则表达式内部,可用\k<name>引用同一个命名捕获组,匹配重复内容:
// 匹配重复单词,比如 "hello hello" const repeatRegex = /(?<word>\w+) \k<word>/; console.log(repeatRegex.test('hello hello')); // 输出 true
- 替换时引用命名组
使用replace()方法时,可用$<name>的形式在替换字符串中调用捕获内容:
const urlStr = 'github.com/octocat/hello-world/main'; const result = urlStr.replace(regex, '仓库:$<repo>,拥有者:$<root>,分支:$<branch>'); console.log(result); // 输出 "仓库:hello-world,拥有者:octocat,分支:main"
内容的提问来源于stack exchange,提问作者Sunil Kumar Singh
相关产品推荐
相关产品推荐

