ZBLOG

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

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

示例 1: 捕获邮箱地址

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. text := "Please contact us at support@example.com or sales@example.com."
  8. pattern := `([\w\.-]+)@([\w\.-]+)` // 捕获用户名和域名
  9. re := regexp.MustCompile(pattern)
  10. matches := re.FindAllStringSubmatch(text, -1)
  11. for _, match := range matches {
  12. fmt.Printf("Full match: %s, Username: %s, Domain: %s\n", match[0], match[1], match[2])
  13. }
  14. }

输出:

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

示例 2: 捕获日期格式

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

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. text := "The events are scheduled on 2023-01-15 and 2023-02-20."
  8. pattern := `(\d{4})-(\d{2})-(\d{2})` // 捕获年、月、日
  9. re := regexp.MustCompile(pattern)
  10. matches := re.FindAllStringSubmatch(text, -1)
  11. for _, match := range matches {
  12. fmt.Printf("Full match: %s, Year: %s, Month: %s, Day: %s\n", match[0], match[1], match[2], match[3])
  13. }
  14. }

输出:

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

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. url := "https://www.example.com/path/to/resource?query=123"
  8. pattern := `^(https?://)([^/]+)(/.*)?$` // 捕获协议、主机名和路径
  9. re := regexp.MustCompile(pattern)
  10. match := re.FindStringSubmatch(url)
  11. if len(match) > 0 {
  12. fmt.Printf("Protocol: %s\nHost: %s\nPath: %s\n", match[1], match[2], match[3])
  13. } else {
  14. fmt.Println("No matches found.")
  15. }
  16. }

输出:

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

小结

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?