ZBLOG

golang正则表达式捕获分组示例

在 Go 语言中,正则表达式支持捕获分组,可以使用括号 () 来创建分组。捕获的内容可以通过 FindStringSubmatch 函数来获取。下面是一些示例,展示如何在 Go 中使用正则表达式的捕获分组。

示例 1: 捕获邮箱地址

package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "Please contact us at support@example.com or sales@example.com."
	pattern := `([\w\.-]+)@([\w\.-]+)` // 捕获用户名和域名

	re := regexp.MustCompile(pattern)
	matches := re.FindAllStringSubmatch(text, -1)

	for _, match := range matches {
		fmt.Printf("Full match: %s, Username: %s, Domain: %s\n", match[0], match[1], match[2])
	}
}

输出:

Full match: support@example.com, Username: support, Domain: example.com
Full match: sales@example.com, Username: sales, Domain: example.com

示例 2: 捕获日期格式

假设我们要从字符串中提取日期信息,日期格式为“YYYY-MM-DD”:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "The events are scheduled on 2023-01-15 and 2023-02-20."
	pattern := `(\d{4})-(\d{2})-(\d{2})` // 捕获年、月、日

	re := regexp.MustCompile(pattern)
	matches := re.FindAllStringSubmatch(text, -1)

	for _, match := range matches {
		fmt.Printf("Full match: %s, Year: %s, Month: %s, Day: %s\n", match[0], match[1], match[2], match[3])
	}
}

输出:

Full match: 2023-01-15, Year: 2023, Month: 01, Day: 15
Full match: 2023-02-20, Year: 2023, Month: 02, Day: 20

示例 3: 从 URL 中提取主机名和路径

如果我们想从 URL 中提取主机名和路径,可以这样做:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	url := "https://www.example.com/path/to/resource?query=123"
	pattern := `^(https?://)([^/]+)(/.*)?$` // 捕获协议、主机名和路径

	re := regexp.MustCompile(pattern)
	match := re.FindStringSubmatch(url)

	if len(match) > 0 {
		fmt.Printf("Protocol: %s\nHost: %s\nPath: %s\n", match[1], match[2], match[3])
	} else {
		fmt.Println("No matches found.")
	}
}

输出:

Protocol: https://
Host: www.example.com
Path: /path/to/resource?query=123

小结

这些示例展示了如何在 Go 中使用正则表达式的捕获分组功能。你可以根据需要修改正则表达式模式以适应不同类型的数据提取需求。如果你有更多具体问题或其他要求,请告诉我!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18865

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?