命名捕获组(Named Capturing Group)

2024-06-24 20:48:16 292
命名捕获组用于捕获匹配结果并为其命名,方便在后续引用和访问。

语法

(?<name>...)

示例

(?<protocol>https?):\/\/(?<domain>[^\/]+)

匹配 https://example.com,捕获 https 为 protocol,example.com 为 domain。

解释:

  • (?<protocol>https?) 捕获 httphttps 并命名为 protocol。
  • (?<domain>[^\/]+) 捕获域名部分并命名为 domain

应用场景

  • 在复杂的正则表达式中,通过命名捕获组可以更加直观地引用捕获的子字符串。
  • 提高代码的可读性和维护性,便于调试和理解。

代码示例

Python

import re

pattern = r'(?P<protocol>https?):\/\/(?P<domain>[^\/]+)'
test_string = 'https://example.com'
match = re.search(pattern, test_string)
if match:
    print(match.group('protocol'))  # 输出: https
    print(match.group('domain'))    # 输出: example.com

JavaScript

const pattern = /(?<protocol>https?):\/\/(?<domain>[^\/]+)/;
const testString = 'https://example.com';
const match = testString.match(pattern);
if (match) {
    console.log(match.groups.protocol);  // 输出: https
    console.log(match.groups.domain);    // 输出: example.com
}