完成了剩下的正则书写
This commit is contained in:
41
7.3.md
41
7.3.md
@@ -189,8 +189,45 @@ Compile和CompilePOSIX不同就是POSIX必须使用POSIX语法,然后他使用
|
||||
fmt.Println(submatchallindex)
|
||||
}
|
||||
|
||||
|
||||
|
||||
我们前面介绍过匹配函数,那么Regexp对象也有这三个函数,和上面外部的三个函数功能一模一样,上面三个外部的函数其实内部实现就是调用了这三个函数:
|
||||
|
||||
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
|
||||
|
||||
这些替换函数我们在上面的抓网页的例子有详细应用示例,
|
||||
|
||||
接下来我们看一下Expand的解释:
|
||||
|
||||
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
|
||||
|
||||
那么这个Expand到底用来干嘛的呢?请看下面的例子:
|
||||
|
||||
func main() {
|
||||
src := []byte(`
|
||||
call hello alice
|
||||
hello bob
|
||||
call hello eve
|
||||
`)
|
||||
pat := regexp.MustCompile(`(?m)(call)\s+(?P<cmd>\w+)\s+(?P<arg>.+)\s*$`)
|
||||
res := []byte{}
|
||||
for _, s := range pat.FindAllSubmatchIndex(src, -1) {
|
||||
res = pat.Expand(res, []byte("$cmd('$arg')\n"), src, s)
|
||||
}
|
||||
fmt.Println(string(res))
|
||||
}
|
||||
|
||||
至此我们已经全部介绍完Go语言的`regexp`包,通过上面对他的每个函数的介绍以及通过例子来演示,大家应该能够通过Go语言的正则包进行基本一些正则的操作了。
|
||||
|
||||
|
||||
## links
|
||||
|
||||
Reference in New Issue
Block a user