go package學習——regexp

package regexp實現了正則表達式的搜索。 正則表達式

Index

Examples

Package Files

exec.go regexp.go 安全

1. 通用函數 併發

func Match

func Match(pattern string, b []byte) (matched bool, err error)
判斷一個文本正則表達式是否與一個byte類型的slice匹配。

func MatchReader

func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
判斷一個文本正則表達式是否與一個由 RuneReader讀取的文本匹配。

func MatchString

func MatchString(pattern string, s string) (matched bool, err error)
判斷一個文本正則表達式是否與一個string匹配。

func QuoteMeta

func QuoteMeta(s string) string
返回s的全部元字符組成的正則表達式。

2. type Regexp app

type Regexp

type Regexp struct {      // contains filtered or unexported fields }
Regexp表明了一個能夠編譯的正則表達式。Regexp同時被多個goroutine使用是安全的。

func Compile

func Compile(expr string) (*Regexp, error)
Compile解析一個正則表達式並返回。

func MustCompile

func MustCompile(str string) *Regexp
相似Compile,但若是沒法解析就會panic。

func (*Regexp) Expand

func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
Expand將template追加到dst中並返回結果。在追加過程當中,Expand根據match,將template中相應的字段替換成src中的字段。

func (*Regexp) Find

func (re *Regexp) Find(b []byte) []byte
返回與b相匹配的第一個最大匹配表達式。

func (*Regexp) Match

func (re *Regexp) Match(b []byte) bool

判斷是否與b相匹配。 函數

以點帶面,其它包在開發過程當中本身學習吧。記住,必定要多動手,纔能有更深的體會。 學習

// regexp.go


------------------------------------------------------------


// 判斷在 b 中可否找到正則表達式 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
}


------------------------------------------------------------


// 判斷在 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
}


------------------------------------------------------------


// 判斷在 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
}


------------------------------------------------------------


// QuoteMeta 將字符串 s 中的「特殊字符」轉換爲其「轉義格式」
// 例如,QuoteMeta(`[foo]`)返回`\[foo\]`。
// 特殊字符有:\.+*?()|[]{}^$
// 這些字符用於實現正則語法,因此看成普通字符使用時須要轉換
func QuoteMeta(s string) string


func main() {
fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))
// \(\?P:Hello\) \[a-z\]
}


------------------------------------------------------------


// Regexp 結構表示一個編譯後的正則表達式
// Regexp 的公開接口都是經過方法實現的
// 多個 goroutine 併發使用一個 RegExp 是安全的
type Regexp struct {
// 私有字段
}


// 經過 Complite、CompilePOSIX、MustCompile、MustCompilePOSIX
// 四個函數能夠建立一個 Regexp 對象


------------------------------------------------------------


// 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",
}


------------------------------------------------------------


// CompilePOSIX 的做用和 Compile 同樣
// 不一樣的是,CompilePOSIX 使用 POSIX 語法,
// 同時,它採用最左最長方式搜索,
// 而 Compile 採用最左最短方式搜索
// POSIX 語法不支持 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"
}


------------------------------------------------------------


// MustCompile 的做用和 Compile 同樣
// 不一樣的是,當正則表達式 str 不合法時,MustCompile 會拋出異常
// 而 Compile 僅返回一個 error 值
func MustCompile(str string) *Regexp


func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// Hello
}


------------------------------------------------------------


// MustCompilePOSIX 的做用和 CompilePOSIX 同樣
// 不一樣的是,當正則表達式 str 不合法時,MustCompilePOSIX 會拋出異常
// 而 CompilePOSIX 僅返回一個 error 值
func MustCompilePOSIX(str string) *Regexp


func main() {
reg := regexp.MustCompilePOSIX(`[[:word:]].+ `)
fmt.Printf("%q\n", reg.FindString("Hello World!"))
// "Hello "
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回第一個匹配的內容
func (re *Regexp) Find(b []byte) []byte


func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.Find([]byte("Hello World!")))
// "Hello"
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回第一個匹配的內容
func (re *Regexp) FindString(s string) string


func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// "Hello"
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回全部匹配的內容
// {{匹配項}, {匹配項}, ...}
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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"]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回全部匹配的內容
// {匹配項, 匹配項, ...}
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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"]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回第一個匹配的位置
// {起始位置, 結束位置}
func (re *Regexp) FindIndex(b []byte) (loc []int)


func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindIndex([]byte("Hello World!")))
// [0 5]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回第一個匹配的位置
// {起始位置, 結束位置}
func (re *Regexp) FindStringIndex(s string) (loc []int)


func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindStringIndex("Hello World!"))
// [0 5]
}


------------------------------------------------------------


// 在 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]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回全部匹配的位置
// {{起始位置, 結束位置}, {起始位置, 結束位置}, ...}
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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]]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回全部匹配的位置
// {{起始位置, 結束位置}, {起始位置, 結束位置}, ...}
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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]]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回第一個匹配的內容
// 同時返回子表達式匹配的內容
// {{完整匹配項}, {子匹配項}, {子匹配項}, ...}
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"]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回第一個匹配的內容
// 同時返回子表達式匹配的內容
// {完整匹配項, 子匹配項, 子匹配項, ...}
func (re *Regexp) FindStringSubmatch(s string) []string


func main() {
reg := regexp.MustCompile(`(\w)(\w)+`)
fmt.Printf("%q", reg.FindStringSubmatch("Hello World!"))
// ["Hello" "H" "o"]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回全部匹配的內容
// 同時返回子表達式匹配的內容
// {
//     {{完整匹配項}, {子匹配項}, {子匹配項}, ...},
//     {{完整匹配項}, {子匹配項}, {子匹配項}, ...},
//     ...
// }
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"]]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回全部匹配的內容
// 同時返回子表達式匹配的內容
// {
//     {完整匹配項, 子匹配項, 子匹配項, ...},
//     {完整匹配項, 子匹配項, 子匹配項, ...},
//     ...
// }
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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"]]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回第一個匹配的位置
// 同時返回子表達式匹配的位置
// {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...}
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]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回第一個匹配的位置
// 同時返回子表達式匹配的位置
// {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...}
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]
}


------------------------------------------------------------


// 在 r 中查找 re 中編譯好的正則表達式,並返回第一個匹配的位置
// 同時返回子表達式匹配的位置
// {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...}
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]
}


------------------------------------------------------------


// 在 b 中查找 re 中編譯好的正則表達式,並返回全部匹配的位置
// 同時返回子表達式匹配的位置
// {
//     {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...},
//     {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...},
//     ...
// }
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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]]
}


------------------------------------------------------------


// 在 s 中查找 re 中編譯好的正則表達式,並返回全部匹配的位置
// 同時返回子表達式匹配的位置
// {
//     {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...},
//     {完整項起始, 完整項結束, 子項起始, 子項結束, 子項起始, 子項結束, ...},
//     ...
// }
// 只查找前 n 個匹配項,若是 n < 0,則查找全部匹配項
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]]
}


------------------------------------------------------------


// 將 template 的內容通過處理後,追加到 dst 的尾部。
// template 中要有 $一、$二、${name1}、${name2} 這樣的「分組引用符」
// match 是由 FindSubmatchIndex 方法返回的結果,裏面存放了各個分組的位置信息
// 若是 template 中有「分組引用符」,則以 match 爲標準,
// 在 src 中取出相應的子串,替換掉 template 中的 $一、$2 等引用符號。
func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte


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


------------------------------------------------------------


// 功能同 Expand 同樣,只不過參數換成了 string 類型
func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte


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


------------------------------------------------------------


// LiteralPrefix 返回全部匹配項都共同擁有的前綴(去除可變元素)
// prefix:共同擁有的前綴
// complete:若是 prefix 就是正則表達式自己,則返回 true,不然返回 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
}


------------------------------------------------------------


// 切換到「貪婪模式」
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))
// Hello
reg.Longest() // 切換到「貪婪模式」
fmt.Printf("%q\n", reg.FindString(text))
// Hello Wo
}


------------------------------------------------------------


// 判斷在 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
}


------------------------------------------------------------


// 判斷在 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
}


------------------------------------------------------------


// 判斷在 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
}


------------------------------------------------------------


// 統計正則表達式中的分組個數(不包括「非捕獲的分組」)
func (re *Regexp) NumSubexp() int


func main() {
reg := regexp.MustCompile(`(?U)(?:Hello)(\s+)(\w+)`)
fmt.Println(reg.NumSubexp())
// 2
}


------------------------------------------------------------


// 在 src 中搜索匹配項,並替換爲 repl 指定的內容
// 所有替換,並返回替換後的結果
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!"
}


------------------------------------------------------------


// 在 src 中搜索匹配項,並替換爲 repl 指定的內容
// 所有替換,並返回替換後的結果
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!"
}


------------------------------------------------------------


// 在 src 中搜索匹配項,並替換爲 repl 指定的內容
// 若是 repl 中有「分組引用符」($一、$name),則將「分組引用符」當普通字符處理
// 所有替換,並返回替換後的結果
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!"
}


------------------------------------------------------------


// 在 src 中搜索匹配項,並替換爲 repl 指定的內容
// 若是 repl 中有「分組引用符」($一、$name),則將「分組引用符」當普通字符處理
// 所有替換,並返回替換後的結果
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!"
}


------------------------------------------------------------


// 在 src 中搜索匹配項,而後將匹配的內容通過 repl 處理後,替換 src 中的匹配項
// 若是 repl 的返回值中有「分組引用符」($一、$name),則將「分組引用符」當普通字符處理
// 所有替換,並返回替換後的結果
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
------------------------------------------------------------


// 在 src 中搜索匹配項,而後將匹配的內容通過 repl 處理後,替換 src 中的匹配項
// 若是 repl 的返回值中有「分組引用符」($一、$name),則將「分組引用符」當普通字符處理
// 所有替換,並返回替換後的結果
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!
}


------------------------------------------------------------


// 在 s 中搜索匹配項,並以匹配項爲分割符,將 s 分割成多個子串
// 最多分割出 n 個子串,第 n 個子串再也不進行分割
// 若是 n < 0,則分割全部子串
// 返回分割後的子串列表
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"]
}


------------------------------------------------------------


// 返回 re 中的「正則表達式」字符串
func (re *Regexp) String() string


func main() {
re := regexp.MustCompile("Hello.*$")
fmt.Printf("%s\n", re.String())
// Hello.*$
}


------------------------------------------------------------


// 返回 re 中的分組名稱列表,未命名的分組返回空字符串
// 返回值[0] 爲整個正則表達式的名稱
// 返回值[1] 是分組 1 的名稱
// 返回值[2] 是分組 2 的名稱
// ……
func (re *Regexp) SubexpNames() []string


func main() {
re := regexp.MustCompile("(?PHello) (World)")
fmt.Printf("%q\n", re.SubexpNames())
// ["" "Name1" ""]
}
ui

相關文章
相關標籤/搜索