English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Functions & Methods

Golang Structs

Golang Slices & Arrays

Golang Strings(String)

Golang Pointers

Golang Interfaces

Golang Concurrency

Golang Exceptions(Error)

Golang Miscellaneous

Go Regex (Regular Expression)

The Go Regex package is used to search strings. To search a string, we need to provide a string pattern.

We need to compile the pattern into the regex object so that we can call the methods through it.

You can use the compile() and mustcompile() functions to retrieve regular expression objects. Now we can use the functions to search strings, such as FindString(), FindStringSubmatch(), FindStringIndex(), etc.

Regular expression example1

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

Output:

.com
.com

The FindString() method returns a string that contains the text of the leftmost match. If no match is found, an empty string is returned.

Regular expression example2

package main
import (
	"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"))
{}

Output:

[6 10]
[]
[2 6]

Regular expression example3

We can also use the FindStringSubmatch() method, which returns a slice of strings containing the leftmost match and the matched text. If no match is found, the return value is an empty string.

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

Output:

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

Common methods in the Go language regular expression regexp package

The Go language regular expression matching can use the Go language regexp package.  

The rules for regular expressions in the Go language are the same as those in other languages, just the functions called are different   

It is recommended to use the `pattern` format when constructing regular expressions.

regexp.Match

// Determine whether a substring matching the regular expression pattern can be found in b
// pattern: the regular expression to search for
// b: The []byte to be searched within
// matched: returns whether a match item is found
// err: returns any errors encountered during the search process
// This function is implemented by calling the method of Regexp
func Match(pattern string, b []byte) (matched bool, err error)

Online example

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

// Determine whether a substring matching the regular expression pattern can be found in s
 // pattern: the regular expression to search for
 // r: the string in which to search
 // matched: returns whether a match item is found
 // err: returns any errors encountered during the search process
 // This function is implemented by calling the method of Regexp
 
 func MatchString(pattern string, s string) (matched bool, err error)

Online example

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 is used to parse whether the regular expression expr is valid, and if valid, it returns a Regexp object
// A Regexp object can perform the required operations on any text
func Compile(expr string) (*Regexp, error)

Returns a pointer to an object that implements the regexp interface, which can be used to call methods defined in regexp, such as Match, MatchString, find, etc.

Online example

//func Compile(expr string) (*Regexp, error)
r, _ := regexp.Compile(`f([a-z]+)`)
 
//func (re *Regexp) Match(b []byte) bool
fmt.Println(r.Match([]byte("foo"))) //true
 
//func (re *Regexp) MatchString(s string) bool
fmt.Println(r.MatchString("foo")) //true
 
//func (re *Regexp) FindString(s string) string
//Only match once
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
//Only match once, the returned result, the value at index 0 is the value of the entire match string, and the second value is the value of the subexpression
fmt.Println(r.FindStringSubmatch("this foo func fan")) //[foo oo]
 
//For FindStringSubmatch, if there is no subexpression in the expression, the subexpression is not checked
demo, _ := regexp.Compile(`foo`)
fmt.Println(demo.FindStringSubmatch("foo")) //[foo]
 
//func (re *Regexp) FindStringSubmatchIndex(s string) []int
fmt.Println(r.FindStringSubmatchIndex("foo func")) //[0 3 1 3]
 
//func (re *Regexp) FindAllString(s string, n int) []string
//n is-1It indicates matching all strings that meet the conditions, n is not-1It indicates matching only n times
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 also indicates the number of matches,-1It indicates matching all
fmt.Println(r.FindAllStringSubmatchIndex("foo func demo fan", -1))
//[[0 3 1 3]] [4 8 5 8]] [14 17 15 17]]
 
//Replacement
 
//func (re *Regexp) ReplaceAll(src []byte, repl []byte) []byte
fmt.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) string
fmt.Println(r.ReplaceAllString("this is foo, that is func, they are fan", "xx"))

regexp.MustCompile has a similar usage to regexp.Compile.

Detailed Explanation of the Go Language Regular Expression regexp Package

// regexp.go Explanation
------------------------------------------------------------
1.Determine if the substring matched by the regular expression pattern can be found in []byte
// pattern: the regular expression to search for
// b: The []byte to be searched within
// matched: returns whether a match item is found
// err: returns any errors encountered during the search process
// This function is implemented by calling the method of Regexp
func Match(pattern string, b []byte) (matched bool, err error)
func main() {
fmt.Println(regexp.Match("H.* ", []byte("Hello World!")))
// true
{}
------------------------------------------------------------
2. Determines whether a substring matching the regular expression pattern can be found in r
// pattern: the regular expression to search for
// r: the RuneReader interface to be searched
// matched: returns whether a match item is found
// err: returns any errors encountered during the search process
// This function is implemented by calling the method of 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. Determines whether a substring matching the regular expression pattern can be found in s
// pattern: the regular expression to search for
// r: the string in which to search
// matched: returns whether a match item is found
// err: returns any errors encountered during the search process
// This function is implemented by calling the method of Regexp
func MatchString(pattern string, s string) (matched bool, err error)
func main() {
fmt.Println(regexp.Match("H.* ", "Hello World!"))
// true
{}
------------------------------------------------------------
4. QuoteMeta converts the 'special characters' in the string s to their 'escaped format'
// For example, QuoteMeta(`[foo]`) returns `
foo
`.
// Special characters include: \.+*?()|[]{}^$
// These characters are used to implement regular expression syntax, so they need to be converted when used as ordinary characters
func QuoteMeta(s string) string
func main() {
fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))
// \?P:Hello
a-z
{}
------------------------------------------------------------
5.Regexp struct represents a compiled regular expression
// The public interfaces of Regexp are all implemented through methods
// Multiple goroutines can safely use a single RegExp
type Regexp struct {
// Private fields
{}
// Through Complite, CompilePOSIX, MustCompile, MustCompilePOSIX
// Four functions can create a Regexp object
------------------------------------------------------------
6.Compile is used to parse the regular expression expr to check if it is valid. If valid, it returns a Regexp object
// A Regexp object can perform the required operations on any text
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 has the same function as Compile
// The difference is that CompilePOSIX uses POSIX syntax
// At the same time, it uses the leftmost longest search method
// While Compile uses the leftmost shortest search method
// POSIX syntax does not support Perl syntax format: \d, \D, \s, \S, \w, \W
func 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 has the same function as Compile
// The difference is that when the regular expression str is invalid, MustCompile will throw an exception
// While Compile only returns an error value
func MustCompile(str string) *Regexp
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// Hello
{}
------------------------------------------------------------
9.MustCompilePOSIX has the same function as CompilePOSIX
// The difference is that when the regular expression str is invalid, MustCompilePOSIX will throw an exception
// While CompilePOSIX only returns an error value
func MustCompilePOSIX(str string) *Regexp
func main() {
reg := regexp.MustCompilePOSIX(`[[:word:]].+ `)
fmt.Printf("%q\n", reg.FindString("Hello World!"))
// "Hello"
{}
------------------------------------------------------------
10Find the first match of the compiled regular expression re in []byte and return the content
func (re *Regexp) Find(b []byte) []byte
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.Find([]byte("Hello World!")))
// "Hello"
{}
------------------------------------------------------------
11Find the first match of the compiled regular expression re in string and return the content
func (re *Regexp) FindString(s string) string
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// "Hello"
{}
------------------------------------------------------------
12.In []byte, search for the compiled regular expression in re and return all matching content
// {{match item}, {match item}, ...
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAll(b []byte, n int) [][]byte
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.FindAll([]byte("Hello World!"), -1))
// ["Hello" "World"]
{}
------------------------------------------------------------
13Find all the match content in the string 're' and return it
// {match item, match item, ...
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllString(s string, n int) []string
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.FindAllString("Hello World!", -1))
// ["Hello" "World"]
{}
------------------------------------------------------------
14. In []byte, search for the compiled regular expression in re and return the position of the first match
// {start position, end position}
func (re *Regexp) FindIndex(b []byte) (loc []int)
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindIndex([]byte("Hello World!")))
// [0 5]
{}
------------------------------------------------------------
15. In string, search for the compiled regular expression in re and return the position of the first match
// {start position, end position}
func (re *Regexp) FindStringIndex(s string) (loc []int)
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindStringIndex("Hello World!"))
// [0 5]
{}
------------------------------------------------------------
16.Find the first match of the compiled regular expression re in r and return the position
// {start position, end position}
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.Find all positions of the compiled regular expression re in []byte and return them
// {{start position, end position}, {start position, end position}, ...
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindAllIndex([]byte("Hello World!"), -1))
// [[0 5]] [6 11]]
{}
------------------------------------------------------------
18.Find all positions of the compiled regular expression re in string and return them
// {{start position, end position}, {start position, end position}, ...
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindAllStringIndex("Hello World!", -1))
// [[0 5]] [6 11]]
{}
------------------------------------------------------------
19Find the first match content of the compiled regular expression in the []byte and return it
// Also return the content of the subexpression match
// {{Complete match}, {Submatch}, {Submatch}, ...}
func (re *Regexp) FindSubmatch(b []byte) [][]byte
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindSubmatch([]byte("Hello World!")))
// ["Hello" "H" "o"]
{}
------------------------------------------------------------
20. Find the first match content of the compiled regular expression in the string 're' and return it
// Also return the content of the subexpression match
// {Complete match, Submatch, Submatch, ...}
func (re *Regexp) FindStringSubmatch(s string) []string
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindStringSubmatch("Hello World!"))
// ["Hello" "H" "o"]
{}
------------------------------------------------------------
21Find all the match content in the []byte and return it
// Also return the content of the subexpression match
// {
// {{Complete match}, {Submatch}, {Submatch}, ...},
// {{Complete match}, {Submatch}, {Submatch}, ...},
// ...
// {}
func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindAllSubmatch([]byte("Hello World!", -1))
// [["Hello" "H" "o"] ["World" "W" "d"]]
{}
------------------------------------------------------------
22Find all the match content in the string 're' and return it
// Also return the content of the subexpression match
// {
// {Complete match, Submatch, Submatch, ...},
// {Complete match, Submatch, Submatch, ...},
// ...
// {}
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindAllStringSubmatch("Hello World!", -1))
// [["Hello" "H" "o"] ["World" "W" "d"]]
{}
------------------------------------------------------------
23Find the first match position of the compiled regular expression in the []byte and return it
// and return the position of the sub-expression match
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...}
func (re *Regexp) FindSubmatchIndex(b []byte) []int
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindSubmatchIndex([]byte("Hello World!")))
// [0 5 0 1 4 5]
{}
------------------------------------------------------------
24Find the first match position of the compiled regular expression in the string 're' and return it
// and return the position of the sub-expression match
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...}
func (re *Regexp) FindStringSubmatchIndex(s string) []int
func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindStringSubmatchIndex("Hello World!",
// [0 5 0 1 4 5]
{}
------------------------------------------------------------
25.Find the first match of the compiled regular expression re in r and return the position
// and return the position of the sub-expression match
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...}
func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
func main() {
r := bytes.NewReader([]byte("Hello World!"))
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Println(reg.FindReaderSubmatchIndex(r))
// [0 5 0 1 4 5]
{}
------------------------------------------------------------
26.Find all positions of the compiled regular expression re in []byte and return them
// and return the position of the sub-expression match
// {
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...},
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...},
// ...
// {}
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
func 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.Find all positions of the compiled regular expression re in string and return them
// and return the position of the sub-expression match
// {
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...},
// {start of full match, end of full match, start of submatch, end of submatch, start of submatch, end of submatch, ...},
// ...
// {}
// Only find the first n matches, if n < 0, then find all matches
func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
func 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. After processing the content of template, append it to the end of dst
// The template must contain a $1、$2, ${name1}, ${name2Such 'group reference symbols' are in the format of }
// Match is the result returned by the FindSubmatchIndex method, which contains the position information of each group.
// If there is a 'group reference symbol' in the template, then use match as the standard.
// Extract the corresponding substring from src and replace it in the template's $1、$2 etc. quotation marks.
func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
func main() {
reg := regexp.MustCompile(`(\w+),(\w+)`)
src := []byte("Golang,World!") // Source text
dst := []byte("Say:") // Target text
template := []byte("Hello $1, Hello $2") // Template
match := reg.FindSubmatchIndex(src) // Parse the source text
// Fill in the template and append it to the target text
fmt.Printf("%q", reg.Expand(dst, template, src, match))
// "Say: Hello Golang, Hello World"
{}
------------------------------------------------------------
31. The function is the same as Expand, but the parameters are changed to string type
func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
func main() {
reg := regexp.MustCompile(`(\w+),(\w+)`)
src := "Golang,World!" // Source text
dst := []byte("Say:") // Target text (writable)
template := "Hello $1, Hello $2" // Template
match := reg.FindStringSubmatchIndex(src) // Parse the source text
// Fill in the template and append it to the target text
fmt.Printf("%q", reg.ExpandString(dst, template, src, match))
// "Say: Hello Golang, Hello World"
{}
------------------------------------------------------------
32. LiteralPrefix returns the common prefix shared by all matches (excluding variable elements)
// prefix: Common prefix
// complete: If prefix is the entire regular expression, return true, otherwise return false
func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
func main() {
reg := regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.LiteralPrefix())
// Hello false
reg = regexp.MustCompile(`Hello`)
fmt.Println(reg.LiteralPrefix())
// Hello true
{}
------------------------------------------------------------
33Switch to 'greedy mode'
func (re *Regexp) Longest()
func main() {
text := `Hello World, 123 Go!`
pattern := `(?U)H[\w\s]+o` // Regular expression flag 'non-greedy mode' (?U)
reg := regexp.MustCompile(pattern)
fmt.Printf("%q\n", reg.FindString(text))
// Hello
reg.Longest() // Switch to 'greedy mode'
fmt.Printf("%q\n", reg.FindString(text))
// Hello Wo
{}
------------------------------------------------------------
34Determine if a match can be found in b
func (re *Regexp) Match(b []byte) bool
func main() {
b := []byte(`Hello World`)
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.Match(b))
// false
reg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.Match(b))
// true
{}
------------------------------------------------------------
35Determine if a match can be found in r
func (re *Regexp) MatchReader(r io.RuneReader) bool
func main() {
r := bytes.NewReader([]byte(`Hello World`))
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.MatchReader(r))
// false
r.Seek(0, 0)
reg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.MatchReader(r))
// true
{}
------------------------------------------------------------
36Determine if a match can be found in s
func (re *Regexp) MatchString(s string) bool
func main() {
s := `Hello World`
reg := regexp.MustCompile(`Hello\w+`)
fmt.Println(reg.MatchString(s))
// false
reg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.MatchString(s))
// true
{}
------------------------------------------------------------
37Count the number of groups in the regular expression (excluding 'non-capturing groups')
func (re *Regexp) NumSubexp() int
func main() {
reg := regexp.MustCompile(`(?U)(?:Hello)(\s+)(\w+)`)
fmt.Println(reg.NumSubexp())
// 2
{}
------------------------------------------------------------
38.Search for the match in 'src' and replace it with the content specified by 'repl'
// Replace all and return the result
func (re *Regexp) ReplaceAll(src, repl []byte) []byte
func 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.Search for the match in 'src' and replace it with the content specified by 'repl'
// Replace all and return the result
func (re *Regexp) ReplaceAllString(src, repl string) string
func 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. Search for the match in 'src' and replace it with the content specified by 'repl'
// If 'repl' contains a 'grouping reference symbol' (1If the group reference is followed by a literal character, the group reference is treated as a regular character
// Replace all and return the result
func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
func 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.Search for the match in 'src' and replace it with the content specified by 'repl'
// If 'repl' contains a 'grouping reference symbol' (1If the group reference is followed by a literal character, the group reference is treated as a regular character
// Replace all and return the result
func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
func 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.Search for the match in 'src', then replace the matched content with the processed result of 'repl' in 'src'
// If the return value of 'repl' contains a 'grouping reference symbol' (1If the group reference is followed by a literal character, the group reference is treated as a regular character
// Replace all and return the result
func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
func 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.Search for the match in 'src', then replace the matched content with the processed result of 'repl' in 'src'
// If the return value of 'repl' contains a 'grouping reference symbol' (1If the group reference is followed by a literal character, the group reference is treated as a regular character
// Replace all and return the result
func (re *Regexp ReplaceAllStringFunc(src string, repl func(string) string) string
func 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.Search for a match in s and split s into multiple substrings using the match as the delimiter
// Split at most n substrings, the nth substring will not be split
// If n < 0, split all substrings
// Returns the list of substrings after splitting
func (re *Regexp Split(s string, n int) []string
func main() {
s := "Hello World\tHello\nGolang"
reg := regexp.MustCompile(`\s`)
fmt.Printf("%q\n", reg.Split(s, -1))
// ["Hello" "World" "Hello" "Golang"]
{}
------------------------------------------------------------
44.Returns the 'regular expression' string in re
func (re *Regexp String() string
func main() {
re := regexp.MustCompile("Hello.*$")
fmt.Printf("%s\n", re.String())
// Hello.*$
{}
------------------------------------------------------------
45.Returns the list of group names in re, empty string for unnamed groups
// The return value [0] is the name of the entire regular expression
// The return value [1] is a group 1 The name
// The return value [2] is a group 2 The name
// ……
func (re *Regexp SubexpNames() []string
func main() {
re := regexp.MustCompile("(?PHello) (World)")
fmt.Printf("%q\n", re.SubexpNames())
// "Name"1" "
{}