阅读 557

Go Regex(正则表达式)

Go Regex包用于搜索字符串。要搜索字符串,我们需要提供字符串模式。

我们需要将模式编译到regex对象中,以便我们可以通过它调用方法。

可以使用compile()和mustcompile()函数来检索正则表达式对象。现在我们可以使用函数来查找字符串,例如FindString(),FindStringSubmatch(),FindStringIndex()等。

正则表达式示例1

示例

package mainimport (
	"fmt"
	"regexp"
)func main() {	re := regexp.MustCompile(".com")
	fmt.Println(re.FindString("nhooo.com"))
	fmt.Println(re.FindString("abc.org"))
	fmt.Println(re.FindString("fb.com"))
}

输出:

.com.com

FindString()方法返回一个字符串,该字符串具有最左边匹配的文本。如果找不到匹配项,则返回空字符串。

正则表达式示例2

示例

package mainimport (
	"fmt"
	"regexp"
)func main() {	re := regexp.MustCompile(".com")
	fmt.Println(re.FindStringIndex("google.com"))
	fmt.Println(re.FindStringIndex("abc.org"))
	fmt.Println(re.FindStringIndex("fb.com"))
}

输出:

[6 10]
[]
[2 6]

正则表达式示例3

我们还可以使用FindStringSubmatch()方法,该方法返回具有最左边匹配项和匹配项文本的字符串切片。如果找不到匹配项,则返回值为空字符串。

示例

package mainimport (
	"fmt"
	"regexp"
)func main() {	re := regexp.MustCompile("f([a-z]+)ing")
	fmt.Println(re.FindStringSubmatch("flying"))
	fmt.Println(re.FindStringSubmatch("abcfloatingxyz"))
}

输出:

[flying ly][floating loat]Process finished with exit code 0

Go 语言正则表达式 regexp 包中常用方法

go语言的正则表达式匹配,可以使用go语言的regexp包。  

go语言的正则表达式和其他语言的正则表达式规则都是一样的,只是调用的函数不同而已   

推荐在构造正则表达式时,使用` pattern `格式。

regexp.Match

// 判断在 b 中能否找到正则表达式 pattern 所匹配的子串// pattern:要查找的正则表达式// b:要在其中进行查找的 []byte// matched:返回是否找到匹配项// err:返回查找过程中遇到的任何错误// 此函数通过调用 Regexp 的方法实现func Match(pattern string, b []byte) (matched bool, err error)

在线示例

package main
 import (
    "fmt"    "regexp")
 func main() {
    matched, err := regexp.Match("^abc.*z$", []byte("abcdefgz"))
    fmt.Println(matched, err) //true nil 
    matched, err = regexp.Match("^abc.*z$", []byte("bcdefgz"))
    fmt.Println(matched, err) //false nil}

regexp.MatchString

// 判断在 s 中能否找到正则表达式 pattern 所匹配的子串 // pattern:要查找的正则表达式 // r:要在其中进行查找的字符串 // matched:返回是否找到匹配项 // err:返回查找过程中遇到的任何错误 // 此函数通过调用 Regexp 的方法实现 
 func MatchString(pattern string, s string) (matched bool, err error)

在线示例

package main
 import (
    "fmt"    "regexp")
 func main() {
    matched, err := regexp.MatchString("^abc.*z$", "abcdefgz")
    fmt.Println(matched, err) //true <nil> 
    matched, err = regexp.MatchString("^abc.*z$", "bcdefgz")
    fmt.Println(matched, err) //false <nil>}

regexp.Compile

// Compile 用来解析正则表达式 expr 是否合法,如果合法,则返回一个 Regexp 对象// Regexp 对象可以在任意文本上执行需要的操作func Compile(expr string) (*Regexp, error)

返回一个实现了regexp的对象指针,可以使用返回值调用regexp中定义的方法,如Match,MatchString,find等。

在线示例

//func Compile(expr string) (*Regexp, error)r, _ := regexp.Compile(`f([a-z]+)`)
 //func (re *Regexp) Match(b []byte) boolfmt.Println(r.Match([]byte("foo"))) //true //func (re *Regexp) MatchString(s string) boolfmt.Println(r.MatchString("foo")) //true //func (re *Regexp) FindString(s string) string//只匹配一次fmt.Println(r.FindString("foo func")) //foo //func (re *Regexp) FindStringIndex(s string) (loc []int)fmt.Println(r.FindStringIndex("demo foo func")) //[5 8] //func (re *Regexp) FindStringSubmatch(s string) []string//只匹配一次,返回的结果中,索引为0的值是整个匹配串的值,第二个值是子表达式的值fmt.Println(r.FindStringSubmatch("this foo func fan")) //[foo oo] //对于FindStringSubmatch,如果表达式中没有子表达式,则不检测子表达式demo, _ := regexp.Compile(`foo`)
fmt.Println(demo.FindStringSubmatch("foo")) //[foo] //func (re *Regexp) FindStringSubmatchIndex(s string) []intfmt.Println(r.FindStringSubmatchIndex("foo func")) //[0 3 1 3] //func (re *Regexp) FindAllString(s string, n int) []string//n为-1时,匹配所有符合条件的字符串,n不为-1时,表示只匹配n次fmt.Println(r.FindAllString("foo func fan", -1)) //[foo func fan]fmt.Println(r.FindAllString("foo func fan", 2))  //[foo func] //func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int//n同样是表示匹配的次数,-1表示匹配所有fmt.Println(r.FindAllStringSubmatchIndex("foo func demo fan", -1))//[[0 3 1 3] [4 8 5 8] [14 17 15 17]] //替换 //func (re *Regexp) ReplaceAll(src []byte, repl []byte) []bytefmt.Println(string(r.ReplaceAll([]byte("this is foo, that is func, they are fan"), []byte("x"))))//this is x, that is x, they are x //func (re *Regexp) ReplaceAllString(src string, repl string) stringfmt.Println(r.ReplaceAllString("this is foo, that is func, they are fan", "xx"))

regexp.MustCompile 和上面的regexp.Compile用法相似。

Go语言正则表达式 regexp 包详解

// regexp.go 详解------------------------------------------------------------1.判断在 []byte 中能否找到正则表达式 pattern 所匹配的子串// pattern:要查找的正则表达式// b:要在其中进行查找的 []byte// matched:返回是否找到匹配项// err:返回查找过程中遇到的任何错误// 此函数通过调用 Regexp 的方法实现func Match(pattern string, b []byte) (matched bool, err error)func main() {
fmt.Println(regexp.Match("H.* ", []byte("Hello World!")))// true}

------------------------------------------------------------2. 判断在 r 中能否找到正则表达式 pattern 所匹配的子串// pattern:要查找的正则表达式// r:要在其中进行查找的 RuneReader 接口// matched:返回是否找到匹配项// err:返回查找过程中遇到的任何错误// 此函数通过调用 Regexp 的方法实现func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)func main() {
r := bytes.NewReader([]byte("Hello World!"))
fmt.Println(regexp.MatchReader("H.* ", r))// true}

------------------------------------------------------------3. 判断在 s 中能否找到正则表达式 pattern 所匹配的子串// pattern:要查找的正则表达式// r:要在其中进行查找的字符串// matched:返回是否找到匹配项// err:返回查找过程中遇到的任何错误// 此函数通过调用 Regexp 的方法实现func MatchString(pattern string, s string) (matched bool, err error)func main() {
fmt.Println(regexp.Match("H.* ", "Hello World!"))// true}

------------------------------------------------------------4. QuoteMeta 将字符串 s 中的“特殊字符”转换为其“转义格式”// 例如,QuoteMeta(`[foo]`)返回`foo
`。// 特殊字符有:\.+*?()|[]{}^$// 这些字符用于实现正则语法,所以当作普通字符使用时需要转换func QuoteMeta(s string) stringfunc main() {
fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))// \?P:Helloa−z


}

------------------------------------------------------------5.Regexp 结构表示一个编译后的正则表达式// Regexp 的公开接口都是通过方法实现的// 多个 goroutine 并发使用一个 RegExp 是安全的type Regexp struct {// 私有字段}// 通过 Complite、CompilePOSIX、MustCompile、MustCompilePOSIX// 四个函数可以创建一个 Regexp 对象------------------------------------------------------------6.Compile 用来解析正则表达式 expr 是否合法,如果合法,则返回一个 Regexp 对象// Regexp 对象可以在任意文本上执行需要的操作func Compile(expr string) (*Regexp, error)func main() {
reg, err := regexp.Compile(`\w+`)
fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)// "Hello",}

------------------------------------------------------------7. CompilePOSIX 的作用和 Compile 一样// 不同的是,CompilePOSIX 使用 POSIX 语法,// 同时,它采用最左最长方式搜索,// 而 Compile 采用最左最短方式搜索// POSIX 语法不支持 Perl 的语法格式:\d、\D、\s、\S、\w、\Wfunc CompilePOSIX(expr string) (*Regexp, error)func main() {
reg, err := regexp.CompilePOSIX(`[[:word:]]+`)
fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)// "Hello"}

------------------------------------------------------------8.MustCompile 的作用和 Compile 一样// 不同的是,当正则表达式 str 不合法时,MustCompile 会抛出异常// 而 Compile 仅返回一个 error 值func MustCompile(str string) *Regexpfunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))// Hello}

------------------------------------------------------------9.MustCompilePOSIX 的作用和 CompilePOSIX 一样// 不同的是,当正则表达式 str 不合法时,MustCompilePOSIX 会抛出异常// 而 CompilePOSIX 仅返回一个 error 值func MustCompilePOSIX(str string) *Regexpfunc main() {
reg := regexp.MustCompilePOSIX(`[[:word:]].+ `)
fmt.Printf("%q\n", reg.FindString("Hello World!"))// "Hello "}

------------------------------------------------------------10. 在 []byte中查找 re 中编译好的正则表达式,并返回第一个匹配的内容func (re *Regexp) Find(b []byte) []bytefunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.Find([]byte("Hello World!")))// "Hello"}

------------------------------------------------------------11.在 string 中查找 re 中编译好的正则表达式,并返回第一个匹配的内容func (re *Regexp) FindString(s string) stringfunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))// "Hello"}

------------------------------------------------------------12.在 []byte 中查找 re 中编译好的正则表达式,并返回所有匹配的内容// {{匹配项}, {匹配项}, ...}// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAll(b []byte, n int) [][]bytefunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.FindAll([]byte("Hello World!"), -1))// ["Hello" "World"]}

------------------------------------------------------------13.在 string 中查找 re 中编译好的正则表达式,并返回所有匹配的内容// {匹配项, 匹配项, ...}// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllString(s string, n int) []stringfunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.FindAllString("Hello World!", -1))// ["Hello" "World"]}

------------------------------------------------------------14. 在 []byte 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// {起始位置, 结束位置}func (re *Regexp) FindIndex(b []byte) (loc []int)func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindIndex([]byte("Hello World!")))// [0 5]}

------------------------------------------------------------15. 在 string 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// {起始位置, 结束位置}func (re *Regexp) FindStringIndex(s string) (loc []int)func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindStringIndex("Hello World!"))// [0 5]}

------------------------------------------------------------16.在 r 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// {起始位置, 结束位置}func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)func main() {
r := bytes.NewReader([]byte("Hello World!"))
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindReaderIndex(r))// [0 5]}

------------------------------------------------------------17.在 []byte 中查找 re 中编译好的正则表达式,并返回所有匹配的位置// {{起始位置, 结束位置}, {起始位置, 结束位置}, ...}// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllIndex(b []byte, n int) [][]intfunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindAllIndex([]byte("Hello World!"), -1))// [[0 5] [6 11]]}

------------------------------------------------------------18.在 string 中查找 re 中编译好的正则表达式,并返回所有匹配的位置// {{起始位置, 结束位置}, {起始位置, 结束位置}, ...}// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllStringIndex(s string, n int) [][]intfunc main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindAllStringIndex("Hello World!", -1))// [[0 5] [6 11]]}

------------------------------------------------------------19. 在 []byte 中查找 re 中编译好的正则表达式,并返回第一个匹配的内容// 同时返回子表达式匹配的内容// {{完整匹配项}, {子匹配项}, {子匹配项}, ...}func (re *Regexp) FindSubmatch(b []byte) [][]bytefunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindSubmatch([]byte("Hello World!")))// ["Hello" "H" "o"]}

------------------------------------------------------------20.在 string 中查找 re 中编译好的正则表达式,并返回第一个匹配的内容// 同时返回子表达式匹配的内容// {完整匹配项, 子匹配项, 子匹配项, ...}func (re *Regexp) FindStringSubmatch(s string) []stringfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindStringSubmatch("Hello World!"))// ["Hello" "H" "o"]}

------------------------------------------------------------21. 在 []byte 中查找 re 中编译好的正则表达式,并返回所有匹配的内容// 同时返回子表达式匹配的内容// {// {{完整匹配项}, {子匹配项}, {子匹配项}, ...},// {{完整匹配项}, {子匹配项}, {子匹配项}, ...},// ...// }func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]bytefunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindAllSubmatch([]byte("Hello World!"), -1))// [["Hello" "H" "o"] ["World" "W" "d"]]}

------------------------------------------------------------22.在 string 中查找 re 中编译好的正则表达式,并返回所有匹配的内容// 同时返回子表达式匹配的内容// {// {完整匹配项, 子匹配项, 子匹配项, ...},// {完整匹配项, 子匹配项, 子匹配项, ...},// ...// }// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]stringfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindAllStringSubmatch("Hello World!", -1))// [["Hello" "H" "o"] ["World" "W" "d"]]}

------------------------------------------------------------23.在 []byte 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// 同时返回子表达式匹配的位置// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...}func (re *Regexp) FindSubmatchIndex(b []byte) []intfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindSubmatchIndex([]byte("Hello World!")))// [0 5 0 1 4 5]}

------------------------------------------------------------24.在 string 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// 同时返回子表达式匹配的位置// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...}func (re *Regexp) FindStringSubmatchIndex(s string) []intfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindStringSubmatchIndex("Hello World!"))// [0 5 0 1 4 5]}

------------------------------------------------------------25.在 r 中查找 re 中编译好的正则表达式,并返回第一个匹配的位置// 同时返回子表达式匹配的位置// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...}func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []intfunc main() {
r := bytes.NewReader([]byte("Hello World!"))
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindReaderSubmatchIndex(r))// [0 5 0 1 4 5]}

------------------------------------------------------------26.在 []byte 中查找 re 中编译好的正则表达式,并返回所有匹配的位置// 同时返回子表达式匹配的位置// {// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...},// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...},// ...// }// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]intfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindAllSubmatchIndex([]byte("Hello World!"), -1))// [[0 5 0 1 4 5] [6 11 6 7 10 11]]}

------------------------------------------------------------27.在 string 中查找 re 中编译好的正则表达式,并返回所有匹配的位置// 同时返回子表达式匹配的位置// {// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...},// {完整项起始, 完整项结束, 子项起始, 子项结束, 子项起始, 子项结束, ...},// ...// }// 只查找前 n 个匹配项,如果 n < 0,则查找所有匹配项func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]intfunc main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindAllStringSubmatchIndex("Hello World!", -1))// [[0 5 0 1 4 5] [6 11 6 7 10 11]]}

-----------------------------------------------------------30. 将 template 的内容经过处理后,追加到 dst 的尾部// template 中要有 $1、$2、${name1}、${name2} 这样的“分组引用符”// match 是由 FindSubmatchIndex 方法返回的结果,里面存放了各个分组的位置信息// 如果 template 中有“分组引用符”,则以 match 为标准,// 在 src 中取出相应的子串,替换掉 template 中的 $1、$2 等引用符号。func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []bytefunc main() {
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", reg.Expand(dst, template, src, match))// "Say: Hello Golang, Hello World"}

------------------------------------------------------------31.功能同 Expand 一样,只不过参数换成了 string 类型func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []bytefunc main() {
reg := regexp.MustCompile(`(\w+),(\w+)`)
src := "Golang,World!" // 源文本dst := []byte("Say: ") // 目标文本(可写)template := "Hello $1, Hello $2" // 模板match := reg.FindStringSubmatchIndex(src) // 解析源文本// 填写模板,并将模板追加到目标文本中fmt.Printf("%q", reg.ExpandString(dst, template, src, match))// "Say: Hello Golang, Hello World"}

------------------------------------------------------------32. LiteralPrefix 返回所有匹配项都共同拥有的前缀(去除可变元素)// prefix:共同拥有的前缀// complete:如果 prefix 就是正则表达式本身,则返回 true,否则返回 falsefunc (re *Regexp) LiteralPrefix() (prefix string, complete bool)func main() {
reg := regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.LiteralPrefix())// Hello falsereg = regexp.MustCompile(`Hello`)
fmt.Println(reg.LiteralPrefix())// Hello true}

------------------------------------------------------------33. 切换到“贪婪模式”func (re *Regexp) Longest()func main() {
text := `Hello World, 123 Go!`
pattern := `(?U)H[\w\s]+o` // 正则标记“非贪婪模式”(?U)reg := regexp.MustCompile(pattern)
fmt.Printf("%q\n", reg.FindString(text))// Helloreg.Longest() // 切换到“贪婪模式”fmt.Printf("%q\n", reg.FindString(text))// Hello Wo}

------------------------------------------------------------34.判断在 b 中能否找到匹配项func (re *Regexp) Match(b []byte) boolfunc main() {
b := []byte(`Hello World`)
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.Match(b))// falsereg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.Match(b))// true}

------------------------------------------------------------35.判断在 r 中能否找到匹配项func (re *Regexp) MatchReader(r io.RuneReader) boolfunc main() {
r := bytes.NewReader([]byte(`Hello World`))
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.MatchReader(r))// falser.Seek(0, 0)
reg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.MatchReader(r))// true}

------------------------------------------------------------36.判断在 s 中能否找到匹配项func (re *Regexp) MatchString(s string) boolfunc main() {
s := `Hello World`
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.MatchString(s))// falsereg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.MatchString(s))// true}

------------------------------------------------------------37. 统计正则表达式中的分组个数(不包括“非捕获的分组”)func (re *Regexp) NumSubexp() intfunc main() {
reg := regexp.MustCompile(`(?U)(?:Hello)(\s+)(\w+)`)
fmt.Println(reg.NumSubexp())// 2}

------------------------------------------------------------38.在 src 中搜索匹配项,并替换为 repl 指定的内容// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAll(src, repl []byte) []bytefunc main() {
b := []byte("Hello World, 123 Go!")
reg := regexp.MustCompile(`(Hell|G)o`)
rep := []byte("${1}ooo")
fmt.Printf("%q\n", reg.ReplaceAll(b, rep))// "Hellooo World, 123 Gooo!"}

------------------------------------------------------------39.在 src 中搜索匹配项,并替换为 repl 指定的内容// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAllString(src, repl string) stringfunc main() {
s := "Hello World, 123 Go!"reg := regexp.MustCompile(`(Hell|G)o`)
rep := "${1}ooo"fmt.Printf("%q\n", reg.ReplaceAllString(s, rep))// "Hellooo World, 123 Gooo!"}

-----------------------------------------------------------40.在 src 中搜索匹配项,并替换为 repl 指定的内容// 如果 repl 中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []bytefunc main() {
b := []byte("Hello World, 123 Go!")
reg := regexp.MustCompile(`(Hell|G)o`)
rep := []byte("${1}ooo")
fmt.Printf("%q\n", reg.ReplaceAllLiteral(b, rep))// "${1}ooo World, 123 ${1}ooo!"}

-----------------------------------------------------------41.在 src 中搜索匹配项,并替换为 repl 指定的内容// 如果 repl 中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAllLiteralString(src, repl string) stringfunc main() {
s := "Hello World, 123 Go!"reg := regexp.MustCompile(`(Hell|G)o`)
rep := "${1}ooo"fmt.Printf("%q\n", reg.ReplaceAllLiteralString(s, rep))// "${1}ooo World, 123 ${1}ooo!"}

------------------------------------------------------------42. 在 src 中搜索匹配项,然后将匹配的内容经过 repl 处理后,替换 src 中的匹配项// 如果 repl 的返回值中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []bytefunc main() {
s := []byte("Hello World!")
reg := regexp.MustCompile("(H)ello")
rep := []byte("$0$1")
fmt.Printf("%s\n", reg.ReplaceAll(s, rep))// HelloH World!fmt.Printf("%s\n", reg.ReplaceAllFunc(s,func(b []byte) []byte {
rst := []byte{}
rst = append(rst, b...)
rst = append(rst, "$1"...)return rst
}))// Hello$1 World!}
k
------------------------------------------------------------43.在 src 中搜索匹配项,然后将匹配的内容经过 repl 处理后,替换 src 中的匹配项// 如果 repl 的返回值中有“分组引用符”($1、$name),则将“分组引用符”当普通字符处理// 全部替换,并返回替换后的结果func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) stringfunc main() {
s := "Hello World!"reg := regexp.MustCompile("(H)ello")
rep := "$0$1"fmt.Printf("%s\n", reg.ReplaceAllString(s, rep))// HelloH World!fmt.Printf("%s\n", reg.ReplaceAllStringFunc(s,func(b string) string {return b + "$1"}))// Hello$1 World!}

------------------------------------------------------------43.在 s 中搜索匹配项,并以匹配项为分割符,将 s 分割成多个子串// 最多分割出 n 个子串,第 n 个子串不再进行分割// 如果 n < 0,则分割所有子串// 返回分割后的子串列表func (re *Regexp) Split(s string, n int) []stringfunc main() {
s := "Hello World\tHello\nGolang"reg := regexp.MustCompile(`\s`)
fmt.Printf("%q\n", reg.Split(s, -1))// ["Hello" "World" "Hello" "Golang"]}

------------------------------------------------------------44.返回 re 中的“正则表达式”字符串func (re *Regexp) String() stringfunc main() {
re := regexp.MustCompile("Hello.*$")
fmt.Printf("%s\n", re.String())// Hello.*$}

------------------------------------------------------------45.返回 re 中的分组名称列表,未命名的分组返回空字符串// 返回值[0] 为整个正则表达式的名称// 返回值[1] 是分组 1 的名称// 返回值[2] 是分组 2 的名称// ……func (re *Regexp) SubexpNames() []stringfunc main() {
re := regexp.MustCompile("(?PHello) (World)")
fmt.Printf("%q\n", re.SubexpNames())// ["" "Name1" ""]}


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐