正则表达式
583字约2分钟
2025-02-03
示例一: 长度为5的字符串匹配
package main
import (
"fmt"
"regexp"
)
func main() {
// 定义一个正则表达式
// \b\w{5}\b 匹配单词长度为5的单词
// \b 匹配单词的边界
// \w 匹配单词字符(字母、数字、下划线)
// {5} 匹配5次
re := regexp.MustCompile(`\b\w{5}\b`)
// 定义一个待匹配的字符串
str := "Hello world! This is a test sentence with some words of different lengths."
// 查找匹配的字符串
matches := re.FindAllString(str, -1)
// 输出匹配的结果
fmt.Println("匹配到的单词(长度为5):")
for _, match := range matches {
fmt.Println(match)
}
}
示例二:邮箱匹配
package main
import (
"fmt"
"regexp"
)
func main() {
// 定义一个匹配邮箱地址的正则表达式
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
// 待匹配的字符串
str := "我的邮箱地址是test@example.com,你的是hello.world@mail.com。"
// 查找匹配的字符串
matches := re.FindAllString(str, -1)
// 输出匹配的结果
fmt.Println("匹配到的邮箱地址:")
for _, match := range matches {
fmt.Println(match)
}
}
示例三:匹配URL
// \b: 匹配单词边界,确保 URL 不会在单词内部断开。
// (?:https?|ftp): 使用非捕获组 (?: ... ) 来匹配 http 或 https 或 ftp。
// ://: 匹配 URL 协议部分的 ://。
// [-a-zA-Z0-9+&@#/%?=~_|!:,.;]*: 匹配 URL 中允许的字符,包括字母、数字和一些特殊字符。
// [-a-zA-Z0-9+&@#/%=~_|]: 匹配 URL 中的结尾字符,确保 URL 结尾。
package main
import (
"fmt"
"regexp"
)
func main() {
// 定义一个匹配 URL 的正则表达式
re := regexp.MustCompile(`\b(?:https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]`)
// 待匹配的字符串
str := "这是一个网址:http://www.example.com?control=add&names=aaa,bbb,还有一个:https://www.example.com/path/to/page"
// 查找匹配的字符串
matches := re.FindAllString(str, -1)
// 输出匹配的结果
fmt.Println("匹配到的 URL:")
for _, match := range matches {
fmt.Println(match)
}
}
最后一个示例:匹配日期
package main
import (
"fmt"
"regexp"
)
func main() {
// 定义一个匹配日期的正则表达式
re := regexp.MustCompile(`\d{4}-\d{2}-\d{2}`)
// 待匹配的字符串
str := "今天是2022-01-01,明天是2022-01-02,后天是2022-01-03。"
// 查找匹配的字符串
matches := re.FindAllString(str, -1)
// 输出匹配的结果
fmt.Println("匹配到的日期:")
for _, match := range matches {
fmt.Println(match)
}
}