@@ -189,8 +189,45 @@ Compile和CompilePOSIX不同就是POSIX必须使用POSIX语法,然后他使用
189189 fmt.Println(submatchallindex)
190190 }
191191
192-
193-
192+ 我们前面介绍过匹配函数,那么Regexp对象也有这三个函数,和上面外部的三个函数功能一模一样,上面三个外部的函数其实内部实现就是调用了这三个函数:
193+
194+ func (re *Regexp) Match(b []byte) bool
195+ func (re *Regexp) MatchReader(r io.RuneReader) bool
196+ func (re *Regexp) MatchString(s string) bool
197+
198+ 接下里让我们来了解替换函数是怎么操作的?
199+
200+ func (re *Regexp) ReplaceAll(src, repl []byte) []byte
201+ func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
202+ func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
203+ func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
204+ func (re *Regexp) ReplaceAllString(src, repl string) string
205+ func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
206+
207+ 这些替换函数我们在上面的抓网页的例子有详细应用示例,
208+
209+ 接下来我们看一下Expand的解释:
210+
211+ func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
212+ func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
213+
214+ 那么这个Expand到底用来干嘛的呢?请看下面的例子:
215+
216+ func main() {
217+ src := []byte(`
218+ call hello alice
219+ hello bob
220+ call hello eve
221+ `)
222+ pat := regexp.MustCompile(`(?m)(call)\s+(?P<cmd>\w+)\s+(?P<arg>.+)\s*$`)
223+ res := []byte{}
224+ for _, s := range pat.FindAllSubmatchIndex(src, -1) {
225+ res = pat.Expand(res, []byte("$cmd('$arg')\n"), src, s)
226+ }
227+ fmt.Println(string(res))
228+ }
229+
230+ 至此我们已经全部介绍完Go语言的` regexp ` 包,通过上面对他的每个函数的介绍以及通过例子来演示,大家应该能够通过Go语言的正则包进行基本一些正则的操作了。
194231
195232
196233## links
0 commit comments