如何使用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等示例内容