JavaScript 如何在正则表达式中访问匹配的组
在JavaScript的正则表达式中,使用括号来定义捕获组。捕获组允许提取匹配字符串的特定部分。当正则表达式执行时,可以通过生成的匹配对象访问匹配组。
在本文中,我们将学习如何在JavaScript的正则表达式中访问匹配的组。有两种方法可以访问匹配的组,它们是:
- 使用
exec()
方法 - 使用
match()
方法
方法1:使用exec()
方法
如果存在搜索模式,则返回整个字符串,否则返回空字符串。
const regex = /pattern(g1)(g2)/;
const match = regex.exec(inputString);
匹配的组可以通过数字索引访问。索引0
代表整个匹配字符串,而后续索引代表捕获的组。
示例: 提取日期的部分
Javascript
const regex = /(\d{2})-(\d{2})-(\d{4})/;
const inputString = '27-06-2023';
const match = regex.exec(inputString);
const day = match[1];
const month = match[2];
const year = match[3];
console.log(day);
console.log(month);
console.log(year);
输出
27
06
2023
方法2:使用match()
方法
如果搜索模式存在,则返回true,否则返回false。
const regex = /pattern(g1)(g2)/;
const match = inputString.match(regex);
示例:解析URL:
JavaScript
const regex = /(https?):\/\/([^:/\s]+)(:\d{2,5})?(\/[^\s]*)?/;
const inputString =
'https://www.geeksforgeeks.com:8080/path/to/resource';
const match = regex.exec(inputString);
const protocol = match[1];
const domain = match[2];
const port = match[3];
const path = match[4];
console.log(protocol);
console.log(domain);
console.log(port);
console.log(path);
输出
https
www.geeksforgeeks.com
:8080
/path/to/resource
结论: 要访问JavaScript正则表达式中匹配的组,我们可以使用 exec()
方法或 match()
方法。使用括号定义的捕获组 ()
可以提取匹配字符串的特定部分。一旦有匹配的对象,我们就可以使用数组索引来访问匹配的组。