go正则表达式

正则表达式

前言:这里主要记载go操作正则表达式,若没学过正则表达式,请前往正则表达式30分钟入门教程学习

常用正则表达式.pdf

一.Go regexp包常用API


📌 正则表达式对象创建

1
2
re, err := regexp.Compile(`\d+`)   // 编译正则,返回 error
re := regexp.MustCompile(`\d+`) // 编译正则(失败会 panic,常用)

📌 匹配相关

方法 说明 示例
MatchString(s) 判断是否匹配 re.MatchString("abc123") // true
Match(b []byte) 判断字节切片是否匹配 re.Match([]byte("123"))

📌 查找匹配

方法 返回 示例
FindString(s) 第一个匹配的字符串 "abc123xyz" → 123
FindAllString(s, n) 所有匹配,n=-1 表示不限制 "12 34 56" → [12 34 56]
FindStringIndex(s) 第一个匹配的起止位置 [start, end] "abc123" → [3 6]
FindAllStringIndex(s, n) 所有匹配的起止位置 "12 34" → [[0 2] [3 5]]

📌 捕获分组

方法 返回 示例
FindStringSubmatch(s) 匹配结果 + 分组内容 正则 (\w+)=(\d+),输入 "age=18"["age=18", "age", "18"]
FindAllStringSubmatch(s, n) 所有分组匹配 "a=1 b=2"[[a=1 a 1] [b=2 b 2]]
FindStringSubmatchIndex(s) 分组的起止位置 ["age=18","age","18"] 对应的索引

📌 替换

方法 说明 示例
ReplaceAllString(s, repl) 替换匹配内容 "foo123bar" → fooNUMbar
ReplaceAllStringFunc(s, func) 用函数处理匹配结果再替换 把所有数字加 1

示例:

1
2
3
4
5
6
7
8
re := regexp.MustCompile(`\d+`)
fmt.Println(re.ReplaceAllString("a1 b22 c333", "NUM"))
// 输出: aNUM bNUM cNUM

fmt.Println(re.ReplaceAllStringFunc("a1 b22 c333", func(s string) string {
return "[" + s + "]"
}))
// 输出: a[1] b[22] c[333]

📌 拆分

方法 说明 示例
Split(s, n) 按正则切分字符串 "a,b;c"[ ,;][a b c]

📌 常用例子

1
2
3
4
5
6
7
8
9
10
re := regexp.MustCompile(`\d+`)

fmt.Println(re.MatchString("abc123")) // true
fmt.Println(re.FindString("abc123xyz")) // "123"
fmt.Println(re.FindAllString("a1 b22 c333", -1)) // ["1" "22" "333"]

re2 := regexp.MustCompile(`(\w+)=(\d+)`)
fmt.Println(re2.FindStringSubmatch("age=18")) // ["age=18" "age" "18"]

fmt.Println(re.Split("a,b;c", -1)) // ["a" "b" "c"]

👉 这些 API 基本覆盖了日常工作里 判断、提取、替换、分组 的需求。


二. 常用正则表达式(Go 适用)

1. 邮箱

1
re := regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)

2. 手机号(中国大陆 11 位,以 1 开头)

1
re := regexp.MustCompile(`^1[3-9]\d{9}$`)

3. URL

1
re := regexp.MustCompile(`^(https?://)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w\.-]*)*/?$`)

4. IPv4 地址

1
re := regexp.MustCompile(`^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$`)

5. 身份证号(中国 18 位)

1
re := regexp.MustCompile(`^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$`)

6. 日期(YYYY-MM-DD)

1
re := regexp.MustCompile(`^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$`)

7. 用户名(字母开头,允许字母数字下划线,3–16 位)

1
re := regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]{2,15}$`)

8. 密码(最少 8 位,至少包含大小写字母和数字)

1
re := regexp.MustCompile(`^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$`)

9. 纯数字

1
re := regexp.MustCompile(`^\d+$`)

10. 中文字符

1
re := regexp.MustCompile(`^[\p{Han}]+$`)

⚡ 使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"fmt"
"regexp"
)

func main() {
re := regexp.MustCompile(`^1[3-9]\d{9}$`)
fmt.Println(re.MatchString("13812345678")) // true
fmt.Println(re.MatchString("123456")) // false
}

三.go正则工具库

好嘞 🚀 我给你写一个 Go 正则工具库,把常用规则放在 map[string]*regexp.Regexp 里,你直接用名字就能调用。


📌 正则工具库示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package regexutil

import (
"regexp"
)

// 常用正则表达式字典
var Patterns = map[string]*regexp.Regexp{
"email": regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`),
"phone": regexp.MustCompile(`^1[3-9]\d{9}$`),
"url": regexp.MustCompile(`^(https?://)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w\.-]*)*/?$`),
"ipv4": regexp.MustCompile(`^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$`),
"idcard": regexp.MustCompile(`^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$`),
"date": regexp.MustCompile(`^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$`),
"username": regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]{2,15}$`),
"password": regexp.MustCompile(`^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$`),
"number": regexp.MustCompile(`^\d+$`),
"chinese": regexp.MustCompile(`^[\p{Han}]+$`),
}

// Match 判断字符串是否符合某种规则
func Match(rule string, input string) bool {
if re, ok := Patterns[rule]; ok {
return re.MatchString(input)
}
return false
}

// Find 返回匹配到的第一个内容
func Find(rule string, input string) string {
if re, ok := Patterns[rule]; ok {
return re.FindString(input)
}
return ""
}

// FindAll 返回所有匹配内容
func FindAll(rule string, input string) []string {
if re, ok := Patterns[rule]; ok {
return re.FindAllString(input, -1)
}
return nil
}

📌 使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"regexutil"
)

func main() {
fmt.Println(regexutil.Match("email", "test@example.com")) // true
fmt.Println(regexutil.Match("phone", "13812345678")) // true
fmt.Println(regexutil.Match("url", "https://golang.org")) // true

fmt.Println(regexutil.Find("number", "商品价格: 123 元")) // 123
fmt.Println(regexutil.FindAll("number", "数量: 12, 价格: 34")) // [12 34]
}

[up主专用,视频内嵌代码贴在这]