在 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助手提供,问题来源于学员提问