一. 正则规范

Go正则表达式语法与Perl、Python等语言一样,都采用了RE2语法规范。RE2的目标是能够处理来自不受信任用户的正则表达式,而不存在风险。它的特点是匹配时间与输入字符串的长度呈线性关系。考虑到生产方面,解析器、编译器和执行引擎通过在可配置的预算内工作来限制内存使用量(耗尽时会优雅地失败),并且通过避免递归来避免堆栈溢出 。
实现Perl,PCRE等引擎提供的所有功能不是Golang的目标,它在某些方面也进行了一些取舍,如Go正则不支持反向引用和环顾断言。


二. 正则基础

这里是对RE2语法对简单归纳,具体可参考:维基百科:RE2语法

1. 语法规则

字符: 包括点、枚举、ASCII、Perl类和Unicode类

shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
.                # 任意字符

[字符类]          # 匹配给定的任一字符,如:^[a-z]+$
[^字符类]         # 匹配给定的非任一字符

[:ASCII类名:]    # 类型如:ascii、alpha、digit,upper、word等
[:^ASCII类名:]   # 取反

\小写Perl类名      #\d、\s、\w
\大写Perl类名      #\D、\S、\W 

\pUnicode标识    # 匹配Unicode字符
\PUnicode标识  

\p{Unicode标识}   # 匹配Unicode字符(特指)
\P{Unicode标识} 

数量:?、 +、 *、 {m}、 {m,n}、 exp?(非贪)

shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
x*          # 匹配零个或多个 x,优先匹配更多(贪婪)
x+          # 匹配一个或多个 x,优先匹配更多(贪婪)
x?          # 匹配零个或一个 x,优先匹配一个(贪婪)
x{n,m}      # 匹配 n 到 m 个 x,优先匹配更多(贪婪)
x{n,}       # 匹配 n 个或多个 x,优先匹配更多(贪婪)
x{n}        # 只匹配 n 个 x

x*?         # 匹配零个或多个 x,优先匹配更少(非贪婪)
x+?         # 匹配一个或多个 x,优先匹配更少(非贪婪)
x??         # 匹配零个或一个 x,优先匹配零个(非贪婪)
x{n,m}?     # 匹配 n 到 m 个 x,优先匹配更少(非贪婪)
x{n,}?      # 匹配 n 个或多个 x,优先匹配更少(非贪婪)
x{n}?       # 只匹配 n 个 x

边界: ^、$、\A、\Z、\B、\b

shell
1
2
3
4
5
6
^        # 如果标记 m=true 则匹配行首,否则匹配整个文本的开头(m 默认为 false)
$        # 如果标记 m=true 则匹配行尾,否则匹配整个文本的结尾(m 默认为 false)
\A       # 匹配整个文本的开头,忽略 m 标记
\b       # 匹配单词边界
\B       # 匹配非单词边界
\z       # 匹配整个文本的结尾,忽略 m 标记

分组: |、()

shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
(子表达式)           # 被捕获的组,该组被编号 (子匹配)
(?P<命名>子表达式)    # 被捕获的组,该组被编号且被命名 (子匹配)
(?:子表达式)         # 非捕获的组 (子匹配)
(?标记)             # 在组内设置标记,非捕获,标记影响当前组后的正则表达式
(?标记:子表达式)      # 在组内设置标记,非捕获,标记影响当前组内的子表达式

## 标记的语法是:
xyz  #(设置 xyz 标记)
-xyz #(清除 xyz 标记)
xy-z #(设置 xy 标记, 清除 z 标记)

## 可以设置的标记有:
i       # 不区分大小写 (默认为 false)
m       # 多行模式:让 ^ 和 $ 匹配整个文本的开头和结尾,而非行首和行尾(默认为 false)
s       # 让 . 匹配 \n (默认为 false)
U       # 非贪婪模式:交换 x* 和 x*? 等的含义 (默认为 false)

2. 参考标识

转义

shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
\a            # 匹配响铃符    (相当于 \x07)
              # 注意:正则表达式中不能使用 \b 匹配退格符,因为 \b 被用来匹配单词边界,
              # 可以使用 \x08 表示退格符。
\f            # 匹配换页符    (相当于 \x0C)
\t            # 匹配横向制表符(相当于 \x09)
\n            # 匹配换行符    (相当于 \x0A)
\r            # 匹配回车符    (相当于 \x0D)
\v            # 匹配纵向制表符(相当于 \x0B)
\123          # 匹配 8  进制编码所代表的字符(必须是 3 位数字)
\x7F          # 匹配 16 进制编码所代表的字符(必须是 3 位数字)
\x{10FFFF}    # 匹配 16 进制编码所代表的字符(最大值 10FFFF  )
\Q...\E       # 匹配 \Q 和 \E 之间的文本,忽略文本中的正则语法
\\            # 匹配字符 \

Perl标识符

shell
1
2
3
4
5
6
\d       # 数字 (相当于 [0-9])
\D       # 非数字 (相当于 [^0-9])
\s       # 空白 (相当于 [\t\n\f\r ])
\S       # 非空白 (相当于[^\t\n\f\r ])
\w       # 单词字符 (相当于 [0-9A-Za-z_])
\W       # 非单词字符 (相当于 [^0-9A-Za-z_])

ASCII标识名

shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
[:alnum:]      # 字母数字 (相当于 [0-9A-Za-z])
[:alpha:]      # 字母 (相当于 [A-Za-z])
[:ascii:]      # ASCII 字符集 (相当于 [\x00-\x7F])
[:blank:]      # 空白占位符 (相当于 [\t ])
[:cntrl:]      # 控制字符 (相当于 [\x00-\x1F\x7F])
[:digit:]      # 数字 (相当于 [0-9])
[:graph:]      # 图形字符 (相当于 [!-~])
[:lower:]      # 小写字母 (相当于 [a-z])
[:print:]      # 可打印字符 (相当于 [ -~] 相当于 [ [:graph:]])
[:punct:]      # 标点符号 (相当于 [!-/:-@[-反引号{-~])
[:space:]      # 空白字符(相当于 [\t\n\v\f\r ])
[:upper:]      # 大写字母(相当于 [A-Z])
[:word:]       # 单词字符(相当于 [0-9A-Za-z_])
[:xdigit:]     # 16进制字符集(相当于 [0-9A-Fa-f])

Unicode标识名

shell
 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
C            # -其他-          (other)
Cc           # 控制字符        (control)
Cf           # 格式            (format)
Co           # 私人使用区      (private use)
Cs           # 代理区          (surrogate)
L            # -字母-          (letter)
Ll           # 小写字母        (lowercase letter)
Lm           # 修饰字母        (modifier letter)
Lo           # 其它字母        (other letter)
Lt           # 首字母大写字母  (titlecase letter)
Lu           # 大写字母        (uppercase letter)
M            # -标记-          (mark)
Mc           # 间距标记        (spacing mark)
Me           # 关闭标记        (enclosing mark)
Mn           # 非间距标记      (non-spacing mark)
N            # -数字-          (number)
Nd           # 十進制数字      (decimal number)
Nl           # 字母数字        (letter number)
No           # 其它数字        (other number)
P            # -标点-          (punctuation)
Pc           # 连接符标点      (connector punctuation)
Pd           # 破折号标点符号  (dash punctuation)
Pe           # 关闭的标点符号  (close punctuation)
Pf           # 最后的标点符号  (final punctuation)
Pi           # 最初的标点符号  (initial punctuation)
Po           # 其他标点符号    (other punctuation)
Ps           # 开放的标点符号  (open punctuation)
S            # -符号-          (symbol)
Sc           # 货币符号        (currency symbol)
Sk           # 修饰符号        (modifier symbol)
Sm           # 数学符号        (math symbol)
So           # 其他符号        (other symbol)
Z            # -分隔符-        (separator)
Zl           # 行分隔符        (line separator)
Zp           # 段落分隔符      (paragraph separator)
Zs           # 空白分隔符      (space separator)
shell
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Arabic       # 阿拉伯文
Bopomofo     # 汉语拼音字母
Greek        # 希腊
Georgian     # 格鲁吉亚文
Han          # 汉文
Hangul       # 韩文
Hiragana     # 平假名(日语)
Katakana     # 片假名(日语)
Mongolian    # 蒙古文
Shavian      # 萧伯纳文
Sinhala      # 僧伽罗文
Tamil        # 泰米尔文
Tibetan      # 藏文
...

三. 源码解析

  • regexp包中,分别由包函数和类型方法 提供了正则校验、查找、替换等最基本的方法,可参考regexp源码文档。
go
 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
44
45
46
47
48
49
50
51
52
53
54
55
56
// 包函数,共8个,包括Regexp结构体的4个
func Match(pattern string, b []byte) (matched bool, err error)
func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
func MatchString(pattern string, s string) (matched bool, err error)
func QuoteMeta(s string) string
type Regexp
    // 创建表达式
    func Compile(expr string) (*Regexp, error)
    func CompilePOSIX(expr string) (*Regexp, error)
    func MustCompile(str string) *Regexp
    func MustCompilePOSIX(str string) *Regexp

    // 扩展
    func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
    func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte

    // 查找
    func (re *Regexp) Find(b []byte) []byte
    func (re *Regexp) FindAll(b []byte, n int) [][]byte
    func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
    func (re *Regexp) FindAllString(s string, n int) []string
    func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
    func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
    func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
    func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
    func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
    func (re *Regexp) FindIndex(b []byte) (loc []int)
    func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
    func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
    func (re *Regexp) FindString(s string) string
    func (re *Regexp) FindStringIndex(s string) (loc []int)
    func (re *Regexp) FindStringSubmatch(s string) []string
    func (re *Regexp) FindStringSubmatchIndex(s string) []int
    func (re *Regexp) FindSubmatch(b []byte) [][]byte
    func (re *Regexp) FindSubmatchIndex(b []byte) []int

    // 校验
    func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
    func (re *Regexp) Match(b []byte) bool
    func (re *Regexp) MatchReader(r io.RuneReader) bool
    func (re *Regexp) MatchString(s string) bool

    // 替换
    func (re *Regexp) ReplaceAll(src, repl []byte) []byte
    func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
    func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
    func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
    func (re *Regexp) ReplaceAllString(src, repl string) string
    func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string

    // 其他
    func (re *Regexp) NumSubexp() int
    func (re *Regexp) Longest()
    func (re *Regexp) Split(s string, n int) []string
    func (re *Regexp) String() string
    func (re *Regexp) SubexpNames() []string

源码示例:

go
  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
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
func main() {
   PkgFunc()
   Compiles()
   FindContent()
   FindIndex()
   FindMatch()

   Match()
   Replace()
   Expand()
   Prefix()
   Longest()
}

// 1. 包函数
func PkgFunc() {
   // Match:匹配字节数组
   fmt.Println(regexp.Match("H.* ", []byte("Hello World!")))

   // MatchString:匹配字符串
   fmt.Println(regexp.MatchString("H.* ", "Hello World!"))

   // MatchReader:实现了io.RuneReader(io.Reader)接口
   r := bytes.NewReader([]byte("Hello World!"))
   fmt.Println(regexp.MatchReader("H.* ", r))

   //QuoteMeta:将字符串 s 中的“特殊字符”转换为其“转义格式”
   fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))
}

// 2. 构建正则对象
func Compiles() {
   reg, err := regexp.Compile(`\w+`)
   fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)

   // 将正则表达式限制为POSIX ERE(egrep)语法,并将匹配语义更改为最左最长
   // 同时,它采用最左最长方式搜索,而Compile采用最左最短方式搜索
   // POSIX 语法不支持 Perl 的语法格式:\d、\D、\s、\S、\w、\W
   reg, err = regexp.CompilePOSIX(`[[:word:]]+`)
   fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)

   reg = regexp.MustCompile(`\w+`)
   fmt.Printf("%q\n", reg.FindString("Hello World!"))

   reg = regexp.MustCompilePOSIX(`[[:word:]]+`)
   fmt.Printf("%q\n", reg.FindString("Hello World"))
}

// 3. 查找匹配内容
func FindContent() {
   reg := regexp.MustCompile(`\w+`)

   // 查找第一个匹配项
   fmt.Printf("%q\n", reg.Find([]byte("Hello World!")))
   fmt.Printf("%q\n", reg.FindString("Hello World!"))

   // 查找所有匹配项
   fmt.Printf("%q\n", reg.FindAll([]byte("Hello World!"), -1))
   fmt.Printf("%q\n", reg.FindAllString("Hello World!", -1))
}

// 4. 查找起止索引位
func FindIndex() {
   reg := regexp.MustCompile(`\w+`)

   // 查找第一个匹配项的起止位
   fmt.Println(reg.FindIndex([]byte("Hello World!")))

   fmt.Println(reg.FindStringIndex("Hello World!"))

   r := bytes.NewReader([]byte("Hello World!"))
   fmt.Println(reg.FindReaderIndex(r))

   // 查找所有匹配项的起止位
   fmt.Println(reg.FindAllIndex([]byte("Hello World!"), -1))
   fmt.Println(reg.FindAllStringIndex("Hello World!", -1))
}

// 5. 分组匹配(即{完整匹配项, 子匹配项, 子匹配项, ...})
func FindMatch() {
   reg := regexp.MustCompile(`(\w)(\w)+`) //两个分组匹配

   // 查找匹配项和子匹配项内容
   fmt.Printf("%q\n", reg.FindSubmatch([]byte("Hello World!")))
   fmt.Printf("%q\n", reg.FindStringSubmatch("Hello World!"))

   fmt.Printf("%q\n", reg.FindAllSubmatch([]byte("Hello World!"), -1))
   fmt.Printf("%q\n", reg.FindAllStringSubmatch("Hello World!", -1))

   // 查找匹配项和子匹配项的起止索引位
   fmt.Println(reg.FindSubmatchIndex([]byte("Hello World!")))
   fmt.Println(reg.FindAllStringSubmatchIndex("Hello World!", -1))
   //...
}

// 6. 正则校验
func Match() {
   // Math
   s := []byte(`Hello World`)
   reg := regexp.MustCompile(`Hello[\w\s]+`)
   fmt.Println(reg.Match(s)) //true

   // MatchReader
   reg = regexp.MustCompile(`Hello\w+`)
   r := bytes.NewReader([]byte(`Hello World`))
   fmt.Println(reg.MatchReader(r)) // false

   // MatchString
   reg = regexp.MustCompile(`Hello[\w\s]+`)
   fmt.Println(reg.MatchString("Hello World")) //true
}

// 7. 正则替换
func Replace() {
   // 将【源数据】替换成【模板格式】的数据
   reg := regexp.MustCompile(`(Hell|G)o`)
   src := []byte("Hello World, 123 Go!")
   rep := []byte("${1}ooo")

   // 打印匹配结果
   fmt.Println(reg.FindAllStringSubmatch(string(src), -1))
   //[[Hello Hell] [Go G]]

   // 1. ReplaceAll
   fmt.Printf("%q\n", reg.ReplaceAll(src, rep))
   // "Hellooo World, 123 Gooo!"

   // 2. ReplaceAllString
   fmt.Printf("%q\n", reg.ReplaceAllString(string(src), string(rep)))
   // "Hellooo World, 123 Gooo!"

   // 3. ReplaceAllLiteral 直接替换(不解析模板)
   fmt.Printf("%q\n", reg.ReplaceAllLiteral(src, rep))
   // "${1}ooo World, 123 ${1}ooo!"

   // 4. ReplaceAllLiteralString
   fmt.Printf("%q\n", reg.ReplaceAllLiteralString(string(src), string(rep)))
   // "${1}ooo World, 123 ${1}ooo!"

   // 5. ReplaceAll
   reg = regexp.MustCompile("(H)ello") //Hello H
   src = []byte("Hello World!")
   rep = []byte("$0$1")
   fmt.Printf("%s\n", reg.ReplaceAll(src, rep))
   // HelloH World!

   // 6. ReplaceAllFunc
   fmt.Printf("%s\n", reg.ReplaceAllFunc(src,
      func(b []byte) []byte {
         rst := []byte{}
         rst = append(rst, b...)
         rst = append(rst, "$1"...)
         return rst
      }))
   // Hello$1 World!

   //7. ReplaceAllString
   fmt.Printf("%s\n", reg.ReplaceAllString("Hello World!", "$0$1"))
   // HelloH World!

   // 8. ReplaceAllStringFunc
   fmt.Printf("%s\n", reg.ReplaceAllStringFunc("Hello World!",
      func(b string) string {
         return b + "$1"
      }))
   // Hello$1 World!
}

// 8. 正则追加(将模板追加到目标文本中)
func Expand() {
   reg := regexp.MustCompile(`(\w+),(\w+)`)

   src := []byte("Golang,World!")           // 源文本
   dst := []byte("Say: ")                   // 目标文本
   template := []byte("Hello $1, Hello $2") // 模板
   match := reg.FindSubmatchIndex(src)      // 解析源文本

   fmt.Printf("%q\n", reg.Expand(dst, template, src, match))
   // "Say: Hello Golang, Hello World"
}

// 9. 前缀
func Prefix() {
   // LiteralPrefix 返回所有匹配项都共同拥有的前缀(去除可变元素)
   // prefix:共同拥有的前缀
   // complete:如果 prefix 就是正则表达式本身,则返回 true,否则返回 false

   reg := regexp.MustCompile(`Hello[\w\s]+`)
   fmt.Println(reg.LiteralPrefix()) // Hello false

   reg = regexp.MustCompile(`Hello`)
   fmt.Println(reg.LiteralPrefix()) // Hello true
}

// 10. 贪婪模式
func Longest() {
   text := `Hello World, 123 Go!`
   pattern := `(?U)H[\w\s]+o` // 正则标记“非贪婪模式”(?U)
   reg := regexp.MustCompile(pattern)
   fmt.Printf("%q\n", reg.FindString(text))
   // Hello

   reg.Longest() // 切换到“贪婪模式”
   fmt.Printf("%q\n", reg.FindString(text))
   // Hello Wo
}

四. 示例代码

查找方式

go
 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
func main() {
   var text = `Hello World`
   reg := regexp.MustCompile(`[a-z]+`)

   // 查找整体(string)
   fas := reg.FindAllString(text, -1) 
   fmt.Println(fas)                   //[ello orld]

   // 查找索引(string)
   fai := reg.FindAllStringIndex(text, -1)
   fmt.Println(fai) //[[1 5] [7 11]]

   // 查找子项(match)
   fass := reg.FindAllStringSubmatch(text, -1)
   fmt.Println(fass) //[[ello] [orld]]

   // 查找索引(match)
   fasi := reg.FindAllStringSubmatchIndex(text, -1)
   fmt.Println(fasi) //[[1 5] [7 11]]

   // 汉字索引(按字节)
   text = "你好 World"
   fai = reg.FindAllStringIndex(text, -1)
   fmt.Println(fai) //[[8 12]]
}

正则规则

go
 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
44
45
46
47
func main() {
   //这个测试一个字符串是否符合一个表达式。
   match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
   fmt.Println(match)

   //上面我们是直接使用字符串,但是对于一些其他的正则任务,你需要使用 Compile 一个优化的 Regexp 结构体。
   r, _ := regexp.Compile("p([a-z]+)ch")

   //这个结构体有很多方法。这里是类似我们前面看到的一个匹配测试。
   fmt.Println(r.MatchString("peach"))

   //这是查找匹配字符串的。
   fmt.Println(r.FindString("peach punch"))

   //这个也是查找第一次匹配的字符串的,但是返回的匹配开始和结束位置索引,而不是匹配的内容。
   fmt.Println(r.FindStringIndex("peach punch"))

   //Submatch 返回完全匹配和局部匹配的字符串。例如,这里会返回 p([a-z]+)ch 和 `([a-z]+) 的信息。
   fmt.Println(r.FindStringSubmatch("peach punch"))

   //类似的,这个会返回完全匹配和局部匹配的索引位置。
   fmt.Println(r.FindStringSubmatchIndex("peach punch"))

   //带 All 的这个函数返回所有的匹配项,而不仅仅是首次匹配项。例如查找匹配表达式的所有项。
   fmt.Println(r.FindAllString("peach punch pinch", -1))

   //All 同样可以对应到上面的所有函数。
   fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))

   //这个函数提供一个正整数来限制匹配次数。
   fmt.Println(r.FindAllString("peach punch pinch", 2))

   //上面的例子中,我们使用了字符串作为参数,并使用了如 MatchString 这样的方法。我们也可以提供 []byte参数并将 String 从函数命中去掉。
   fmt.Println(r.Match([]byte("peach")))

   //创建正则表示式常量时,可以使用 Compile 的变体MustCompile 。因为 Compile 返回两个值,不能用语常量。
   r = regexp.MustCompile("p([a-z]+)ch")
   fmt.Println(r)

   //regexp 包也可以用来替换部分字符串为其他值。
   fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))

   //Func 变量允许传递匹配内容到一个给定的函数中,
   in := []byte("a peach")
   out := r.ReplaceAllFunc(in, bytes.ToUpper)
   fmt.Println(string(out))
}
go
 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
func main() {
   text := "Hello World ,你好 GOLANG!"

   // 单词(大小字母、数字、下划线)
   reg := regexp.MustCompile(`[\w]+`)
   ret := reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("1. %q\n", ret)

   // 大写字母
   reg = regexp.MustCompile(`[[:upper:]]+`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("2. %q\n", ret)

   // 非ASCII
   reg = regexp.MustCompile(`[[:^ascii:]]+`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("3. %q\n", ret)

   // 连续标点
   reg = regexp.MustCompile(`[\pP]+`)
   //reg = regexp.MustCompile(`[\PP]+`)  //非标点符号
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("4. %q\n", ret)

   // 连续汉字
   reg = regexp.MustCompile(`[\p{Han}]+`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("5. %q\n", ret)

   // 贪婪模式
   reg = regexp.MustCompile(`^H.*\s`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("6. %q\n", ret)

   // 非贪模式
   reg = regexp.MustCompile(`(?U)^H.*\s`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("7. %q\n", ret)

   // 区分大小写(默认)
   reg = regexp.MustCompile(`[Hw]\w*\s`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("8. %q\n", ret)

   // 忽略大小写
   reg = regexp.MustCompile(`(?i:[hW])\w*\s`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("9. %q\n", ret)

   // 单词边界
   reg = regexp.MustCompile(`(?U)\b.+\b`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("10. %q\n", ret)

   // 数量限定
   reg = regexp.MustCompile(`[^ ]{1,4}o`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("11. %q\n", ret)

   // 子表达式
   reg = regexp.MustCompile(`(?:Hell|W)o`)
   //reg = regexp.MustCompile(`(Hell|W)o`) // [["Hello" "Hell"] ["Wo" "W"]]
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("12. %q\n", ret)

   // 模板替换
   reg = regexp.MustCompile(`(Hello)(.*)(World)`)
   fmt.Printf("13. %q\n", reg.ReplaceAllString(text, "$3$2$1"))

   // 多行模式
   text="abc\nadc\naxy"
   reg = regexp.MustCompile(`(?m:^a.*c$)`)
   //reg = regexp.MustCompile(`(^a.*c$)`)
   ret = reg.FindAllStringSubmatch(text, -1)
   fmt.Printf("10. %q\n", ret)
}

参考链接

https://blog.csdn.net/zfy1355/article/details/52959803
http://www.zhangwenbing.com/blog/golang/BJu7QSkw4
http://www.cnblogs.com/jkko123/p/8329515.html
https://studygolang.com/articles/7256


「真诚赞赏,手留余香」

Hollson码夫庄园

嗯,我的梦想是被读者的稿费包养~

使用微信扫描二维码完成支付

Hollson

评论