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

Tutorial básico do Go

Controles de语句 do Go

Funções & Métodos do Go

Estruturas do Go

Fatias & Arrays do Go

Strings (String) do Go

Ponteiros do Go

Interfaces do Go

Concorrência do Go

Exceções (Error) do Go

Outros itens do Go

Regex (Expressão Regular) do Go

O pacote Regex do Go é usado para procurar strings. Para procurar strings, precisamos fornecer um padrão de string.

Precisamos compilar o padrão no objeto regex para que possamos chamá-lo por meio dele métodos.

Podemos usar as funções compile() e mustcompile() para obter o objeto de expressão regular. Agora podemos usar essas funções para procurar strings, por exemplo, FindString(), FindStringSubmatch(), FindStringIndex(), etc.

Exemplo de expressão regular1

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"))
}

Saída:

.com
.com

O método FindString() retorna uma string que contém o texto da correspondência mais à esquerda. Se não encontrar correspondências, retorna uma string vazia.

Exemplo de expressão regular2

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"))
}

Saída:

[6 10]
[]
[2 6]

Exemplo de expressão regular3

Podemos usar o método FindStringSubmatch(), que retorna uma fatia de strings com o item de correspondência mais à esquerda e o texto do item de correspondência. Se não encontrar correspondências, o valor retornado será uma string vazia.

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

Saída:

[voando ly]
[flutuante float]
Processo finalizado com código de saída 0

Métodos comuns do pacote regexp do idioma Go

A correspondência de expressões regulares do Go pode usar o pacote regexp do Go  

As regras de expressões regulares do Go são as mesmas que as de outros idiomas, apenas as funções chamadas são diferentes   

Recomenda-se usar o formato `pattern` ao construir expressões regulares.

regexp.Match

// Verificar se pode encontrar a substriga correspondente ao padrão regular pattern no b
// pattern: expressão regular a ser encontrada
// b: a byte array where the search is to be performed
// matched: retorna se foi encontrado um item correspondente
// err: retorna qualquer erro encontrado durante a busca
// Essa função é implementada através do método Regexp
func Match(pattern string, b []byte) (matched bool, err error)

Exemplo online

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

// Verificar se pode encontrar a substriga correspondente ao padrão regular pattern no s
 // pattern: expressão regular a ser encontrada
 // r: a string onde será feita a busca
 // matched: retorna se foi encontrado um item correspondente
 // err: retorna qualquer erro encontrado durante a busca
 // Essa função é implementada através do método Regexp
 
 func MatchString(pattern string, s string) (matched bool, err error)

Exemplo online

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 usado para analisar se a expressão regular expr é válida, se for válida, retorna um objeto Regexp
// O objeto Regexp pode executar a operação necessária em qualquer texto
func Compile(expr string) (*Regexp, error)

Retorna um ponteiro para um objeto regexp que implementou, que pode ser chamado usando o valor de retorno para chamar métodos definidos no regexp, como Match, MatchString, find, etc.

Exemplo online

//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
//Apenas correspondência uma vez
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 value at index 0 in the returned result is the value of the entire matched 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, then 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-1when, it matches all strings that meet the conditions, n is not-1when, it means to match 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 means the number of matches,-1means match 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 and regexp.Compile have similar usage.

Detailed Explanation of the Go Language Regular Expression regexp Package

// regexp.go Explanation
------------------------------------------------------------
1.Check if the substring matched by the regular expression pattern can be found in the byte array []byte
// pattern: expressão regular a ser encontrada
// b: a byte array where the search is to be performed
// matched: retorna se foi encontrado um item correspondente
// err: retorna qualquer erro encontrado durante a busca
// Essa função é implementada através do método 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: expressão regular a ser encontrada
// r: o interface RuneReader onde será feita a busca
// matched: retorna se foi encontrado um item correspondente
// err: retorna qualquer erro encontrado durante a busca
// Essa função é implementada através do método 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: expressão regular a ser encontrada
// r: a string onde será feita a busca
// matched: retorna se foi encontrado um item correspondente
// err: retorna qualquer erro encontrado durante a busca
// Essa função é implementada através do método Regexp
func MatchString(pattern string, s string) (matched bool, err error)
func main() {
fmt.Println(regexp.Match("H.* ", "Hello World!"))
// true
}
------------------------------------------------------------
4. QuoteMeta converte os "caracteres especiais" da string s para seu formato de "escape"
// Por exemplo, QuoteMeta(`[foo]`) retorna `
foo
`。
// Caracteres especiais têm: \.+*?()|[]{}^$
// Esses caracteres são usados para implementar a sintaxe regular, portanto, precisam ser convertidos quando usados como caracteres normais
func QuoteMeta(s string) string
func main() {
fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))
// \?P:Hello
a−z
}
------------------------------------------------------------
5.Regexp estrutura representa uma expressão regular compilada
// As interfaces públicas do Regexp são implementadas por meio de métodos
// O uso de múltiplas goroutines com um único RegExp é seguro
type Regexp struct {
// Campos privados
}
// através de Complite, CompilePOSIX, MustCompile, MustCompilePOSIX
// Quatro funções podem criar um objeto Regexp
------------------------------------------------------------
6.Compile é usado para analisar se a expressão regular expr é válida. Se for válida, retorna um objeto Regexp
// O objeto Regexp pode executar a operação necessária em qualquer texto
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 tem a mesma função que Compile
// A diferença é que o CompilePOSIX usa a sintaxe POSIX
// Ao mesmo tempo, ele usa a pesquisa mais à esquerda e mais longa
// Enquanto o Compile usa a pesquisa mais à esquerda e mais curta
// A sintaxe POSIX não suporta a sintaxe do Perl: \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 tem a mesma função que Compile
// A diferença é que, quando a expressão regular str não for válida, MustCompile lançará uma exceção
// Enquanto o Compile apenas retorna um valor de erro
func MustCompile(str string) *Regexp
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// Olá
}
------------------------------------------------------------
9.MustCompilePOSIX tem a mesma função que CompilePOSIX
// A diferença é que, quando a expressão regular str não for válida, MustCompilePOSIX lançará uma exceção
// Enquanto o CompilePOSIX apenas retorna um valor de erro
func MustCompilePOSIX(str string) *Regexp
func main() {
reg := regexp.MustCompilePOSIX(`[[:word:]]+ `)
fmt.Printf("%q\n", reg.FindString("Hello World!"))
// "Hello"
}
------------------------------------------------------------
10. Procurar em []byte a expressão regular compilada no re e retornar o primeiro conteúdo correspondente
func (re *Regexp) Find(b []byte) []byte
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.Find([]byte("Hello World!")))
// "Hello"
}
------------------------------------------------------------
11. Procurar na string string a expressão regular compilada no re e retornar o primeiro conteúdo correspondente
func (re *Regexp) FindString(s string) string
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// "Hello"
}
------------------------------------------------------------
12.在 []byte 中查找 re 中编译好的正则表达式,并返回所有匹配的内容
// {{匹配项}, {匹配项}, ...}
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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"]
}
------------------------------------------------------------
13Procurar por expressão regular compilada em 're' dentro de 'string' e retornar todos os matches
// {匹配项, 匹配项, ...}
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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. 在 []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.Procura pela expressão regular compilada re no r e retorna a primeira posição de correspondência
// {起始位置, 结束位置}
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.Procura pela expressão regular compilada re no []byte e retorna todas as posições de correspondência
// {{起始位置, 结束位置}, {起始位置, 结束位置}, ...}
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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.Procura pela expressão regular compilada re no string e retorna todas as posições de correspondência
// {{起始位置, 结束位置}, {起始位置, 结束位置}, ...}
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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]]
}
------------------------------------------------------------
19Procurar por expressão regular compilada em 're' dentro de '[]byte' e retornar o conteúdo do primeiro match
// ao mesmo tempo, retorna o conteúdo do subexpressão de match
// {{match completo}, {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. Procurar por expressão regular compilada em 're' dentro de 'string' e retornar o conteúdo do primeiro match
// ao mesmo tempo, retorna o conteúdo do subexpressão de match
// {match completo, 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"]
}
------------------------------------------------------------
21Procurar por expressão regular compilada em 're' dentro de '[]byte' e retornar todos os matches
// ao mesmo tempo, retorna o conteúdo do subexpressão de match
// {
// {{match completo}, {submatch}, {submatch}, ...},
// {{match completo}, {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"]]
}
------------------------------------------------------------
22Procurar por expressão regular compilada em 're' dentro de 'string' e retornar todos os matches
// ao mesmo tempo, retorna o conteúdo do subexpressão de match
// {
// {match completo, submatch, submatch, ...},
// {match completo, submatch, submatch, ...},
// ...
// }
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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"]]
}
------------------------------------------------------------
23Procurar por expressão regular compilada em 're' dentro de '[]byte' e retornar a posição do primeiro match
// ao mesmo tempo, retorna a posição da expressão subexpressão
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...}
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]
}
------------------------------------------------------------
24Procurar por expressão regular compilada em 're' dentro de 'string' e retornar a posição do primeiro match
// ao mesmo tempo, retorna a posição da expressão subexpressão
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...}
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.Procura pela expressão regular compilada re no r e retorna a primeira posição de correspondência
// ao mesmo tempo, retorna a posição da expressão subexpressão
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...}
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.Procura pela expressão regular compilada re no []byte e retorna todas as posições de correspondência
// ao mesmo tempo, retorna a posição da expressão subexpressão
// {
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...},
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...},
// ...
// }
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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.Procura pela expressão regular compilada re no string e retorna todas as posições de correspondência
// ao mesmo tempo, retorna a posição da expressão subexpressão
// {
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...},
// {início do item completo, fim do item completo, início do subitem, fim do subitem, início do subitem, fim do subitem, ...},
// ...
// }
// Apenas busca os primeiros n itens de correspondência, se n < 0, busca todas as correspondências
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. Após processar o conteúdo do template, adicione-o ao final do dst
// O template deve ter $1、$2e ${name1e ${name2Tal sinal de referência de grupo
// O match é o resultado retornado pelo método FindSubmatchIndex, que contém informações sobre a posição de cada grupo.
// Se o template tiver um "sinal de referência de grupo", usa-se o match como padrão.
// Extraia a substring correspondente de src e substitua-a no template com o $1、$2 etc. sinais de citação.
func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
func main() {
reg := regexp.MustCompile(`(\w+),(\w+)`)
src := []byte("Golang,World!") // Texto de origem
dst := []byte("Say:") // Texto de destino
template := []byte("Hello $1, Hello $2" // Modelo
match := reg.FindSubmatchIndex(src) // Análise do texto de origem
// Preencha o modelo e junte-o ao texto de destino
fmt.Printf("%q", reg.Expand(dst, template, src, match))
// "Say: Hello Golang, Hello World"
}
------------------------------------------------------------
31. A função é a mesma que Expand, mas os parâmetros são do tipo string
func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
func main() {
reg := regexp.MustCompile(`(\w+),(\w+)`)
src := "Golang,World!" // Texto de origem
dst := []byte("Say:") // Texto de destino (gravável)
template := "Hello $1, Hello $2" // Modelo
match := reg.FindStringSubmatchIndex(src) // Análise do texto de origem
// Preencha o modelo e junte-o ao texto de destino
fmt.Printf("%q", reg.ExpandString(dst, template, src, match))
// "Say: Hello Golang, Hello World"
}
------------------------------------------------------------
32. LiteralPrefix retorna o prefixo comum de todos os itens correspondentes (removendo elementos variáveis)
// prefix: prefixo comum
// complete: se o prefix é a expressão regular em si, retorna true, caso contrário, retorna 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())
// Olá true
}
------------------------------------------------------------
33. Mudar para o "modo destrutivo"
func (re *Regexp) Longest()
func main() {
text := `Olá Mundo, 123 Vamos!`
pattern := `(?U)H[\w\s]+o` // Marcador regular "modo destrutivo" (?U)
reg := regexp.MustCompile(pattern)
fmt.Printf("%q\n", reg.FindString(text))
// Olá
reg.Longest() // Mudar para o "modo destrutivo"
fmt.Printf("%q\n", reg.FindString(text))
// Olá Wo
}
------------------------------------------------------------
34. Determina se há itens correspondentes em b
func (re *Regexp) Match(b []byte) bool
func main() {
b := []byte(`Olá Mundo`)
reg := regexp.MustCompile(`Olá\w+`)
fmt.Println(reg.Match(b))
// false
reg = regexp.MustCompile(`Olá[\w\s]+`)
fmt.Println(reg.Match(b))
// true
}
------------------------------------------------------------
35. Determina se há itens correspondentes em r
func (re *Regexp) MatchReader(r io.RuneReader) bool
func main() {
r := bytes.NewReader([]byte(`Olá Mundo`))
reg := regexp.MustCompile(`Olá\w+`)
fmt.Println(reg.MatchReader(r))
// false
r.Seek(0, 0)
reg = regexp.MustCompile(`Olá[\w\s]+`)
fmt.Println(reg.MatchReader(r))
// true
}
------------------------------------------------------------
36. Determina se há itens correspondentes em s
func (re *Regexp) MatchString(s string) bool
func main() {
s := `Olá Mundo`
reg := regexp.MustCompile(`Olá\w+`)
fmt.Println(reg.MatchString(s))
// false
reg = regexp.MustCompile(`Olá[\w\s]+`)
fmt.Println(reg.MatchString(s))
// true
}
------------------------------------------------------------
37. Conta o número de grupos da expressão regular (não incluindo "grupos não capturados")
func (re *Regexp) NumSubexp() int
func main() {
reg := regexp.MustCompile(`(?U)(?:Olá)(\s+(\w+)`)
fmt.Println(reg.NumSubexp())
// 2
}
------------------------------------------------------------
38.Procurar correspondências no 'src' e substituir por conteúdo especificado por 'repl'
// Substitui tudo e retorna o resultado substituído
func (re *Regexp) Substituição de Tudo(src, repl []byte) []byte
func main() {
b := []byte("Hello World, 123 Go!")
reg := regexp.MustCompile(`(Hell|G)o`)
rep := []byte("${1}"
fmt.Printf("%q\n", reg.Substituição de Tudo por String(b, rep))
// "Hellooo World, 123 Gooo!"
}
------------------------------------------------------------
39.Procurar correspondências no 'src' e substituir por conteúdo especificado por 'repl'
// Substitui tudo e retorna o resultado substituído
func (re *Regexp) Substituição de Tudo por String(src, string de substituição repl) string
func main() {
s := "Hello World, 123 Go!"
reg := regexp.MustCompile(`(Hell|G)o`)
rep := "${1}"
fmt.Printf("%q\n", reg.ReplaceAllString(s, rep))
// "Hellooo World, 123 Gooo!"
}
-----------------------------------------------------------
40.Procurar correspondências no 'src' e substituir por conteúdo especificado por 'repl'
// Se 'repl' contiver o 'sinal de referência de grupo' ($)1e $name), o "sinal de referência de grupo" é tratado como caractere normal }}
// Substitui tudo e retorna o resultado substituído
func (re *Regexp) ReplaceAllLiteral(src, rep []byte) []byte
func main() {
b := []byte("Hello World, 123 Go!")
reg := regexp.MustCompile(`(Hell|G)o`)
rep := []byte("${1}"
fmt.Printf("%q\n", reg.ReplaceAllLiteral(b, rep))
// "${1}ooo World, 123 ${1}ooo!"
}
-----------------------------------------------------------
41.Procurar correspondências no 'src' e substituir por conteúdo especificado por 'repl'
// Se 'repl' contiver o 'sinal de referência de grupo' ($)1e $name), o "sinal de referência de grupo" é tratado como caractere normal }}
// Substitui tudo e retorna o resultado substituído
func (re *Regexp) ReplaceAllLiteralString(src, rep string) string
func main() {
s := "Hello World, 123 Go!"
reg := regexp.MustCompile(`(Hell|G)o`)
rep := "${1}"
fmt.Printf("%q\n", reg.ReplaceAllLiteralString(s, rep))
// "${1}ooo World, 123 ${1}ooo!"
}
------------------------------------------------------------
42.Procurar correspondências no 'src' e substituir o conteúdo correspondente após o processamento por 'repl'
// Se o valor de retorno de 'repl' contiver o 'sinal de referência de grupo' ($)1e $name), o "sinal de referência de grupo" é tratado como caractere normal }}
// Substitui tudo e retorna o resultado substituído
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))
// 
fmt.Printf("%s\n", reg.ReplaceAllFunc(s, ...)
func(b []byte) []byte {
rst := []byte{}
rst = append(rst, b...)
rst = append(rst, "$1"...)
retornar 'rst'
))
// Hello$1 Mundo!
}
k
------------------------------------------------------------
43.Procurar correspondências no 'src' e substituir o conteúdo correspondente após o processamento por 'repl'
// Se o valor de retorno de 'repl' contiver o 'sinal de referência de grupo' ($)1e $name), o "sinal de referência de grupo" é tratado como caractere normal }}
// Substitui tudo e retorna o resultado substituído
func (re *Regexp ReplaceAllStringFunc(src string, repl func(string) string) string
func main() {
s := "Hello Mundo!"
reg := regexp.MustCompile("(H)ello"
rep := "$0$"1"
fmt.Printf("%s\n", reg.ReplaceAllString(s, rep))
// 
fmt.Printf("%s\n", reg.ReplaceAllStringFunc(s,
func(b string) string {
return b + "$1"
))
// Hello$1 Mundo!
}
------------------------------------------------------------
43.Procura correspondências no s e divide s em várias substrings usando a correspondência como separador
// Divide até n substrings, a substring n não é dividida
// Se n < 0, divide todas as substrings
// Retorna a lista de substrings resultantes da divisão
func (re *Regexp Split(s string, n int) []string
func main() {
s := "Hello Mundo\tHello\nGolang"

fmt.Printf("%q\n", reg.Split(s, -1))
// ['Hello' 'Mundo' 'Hello' 'Golang']
}
------------------------------------------------------------
44.Retorna a string do expressão regular no re
func (re *Regexp String string
func main() {
re := regexp.MustCompile("Hello.*$"
fmt.Printf("%s\n", re.String())
// Hello.*$
}
------------------------------------------------------------
45.Retorna a lista de nomes dos grupos do re, os grupos sem nome retornam uma string vazia
// O valor retornado [0] é o nome do expressão regular completa
// O valor retornado [1] é um grupo 1 o nome
// O valor retornado [2] é um grupo 2 o nome
// ……
func (re *Regexp SubexpNames []string
func main() {
re := regexp.MustCompile("(?PHello) (Mundo)")
fmt.Printf("%q\n", re.SubexpNames())
// ["", "Nome"]1""
}