(?<name>...)
(?<protocol>https?):\/\/(?<domain>[^\/]+)
匹配 https://example.com
,捕获 https 为 protocol,example.com 为 domain。
解释:
(?<protocol>https?)
捕获 http
或 https
并命名为 protocol。(?<domain>[^\/]+)
捕获域名部分并命名为 domain
。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
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
}