如何使用Go正則表達式(二)

語言: CN / TW / HK

theme: channing-cyan

攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第25天,點擊查看活動詳情

在上一篇的文章中,介紹了獲取正則對象、匹配檢測、和查找的相關內容和示例,本篇文章繼續擴展Go正則表達式的內容和示例;

查找匹配位置

regexp包提供了FindStringIndex()、FindIndex()、FindAllStringIndex()方法來獲取匹配正則子字符串的位置;

FindIndex()方法

FindIndex()方法用於查找匹配的開始位置和結束位置,如果匹配成功,則返回包含最左側匹配結果的起止位置的切片;

FindIndex()方法的定義格式為:

func (re *Regexp) FindIndex(b []byte)(loc []int)

FindALLIndex()方法

FindAllString()方法用於查找所有匹配的開始位置和結束位置,如果匹配成功,則返回包含最左側匹配結果的起止位置的切片;

FindAllIndex()方法的定義格式為:

func(re *Regexp) FindAllIndex(b []byte, n int) [][]int

FindStringIndex()方法

FindStringIndex()方法用於查找第一次匹配指定子字符串的索引的起始索引和結束索引,如果匹配成功,則返回包含最左側匹配結果的起止位置的切片;

FindStringIndex()方法的定義格式為:

func(re *Regexp) FindStringIndex(s string)(loc []int)

FindAllStringIndex()方法

FindAllStringIndex()方法用於返回包含最左側匹配結果的起止位置的切片;

FindAllStringIndex()方法的定義格式為:

func (re *Regexp) FindAllStringIndex(s string, n int) [][]int

使用示例:

image.png

替換

regexp包中提供了ReplaceAllString()、ReplaceAll()方法來替換字符,它們的定義格式為:

func(re *Regexp) ReplaceAllString(src, repl string) string

func(re *Regexp) ReplaceAll(src, repl []byte) []byte

替換時可以使用反向引用$1、$2來引用匹配的子內容;

替換示例如下圖所示:

image.png

image.png

以上補充了Go正則表達式的查找匹配位置和替換, 最後還有一個分割知識點,我準備寫到下一篇文章中,並列舉一些正則表達式的常見用法————匹配電話號、Email等示例內容