regexp.Compile
或regexp.MustCompile
函数来创建一个正则表达式对象。// 编译正则表达式,返回一个Regexp对象 re, err := regexp.Compile(`\d+`)if err != nil { fmt.Println(err) return } // 使用MustCompile可以简化错误处理,一般用这个 re := regexp.MustCompile(`\d+`)
MatchString
方法来判断字符串是否匹配正则表达式。matched := re.MatchString("123abc") fmt.Println(matched) // 输出: true
FindString
、FindStringIndex
、FindAllString
等方法来查找匹配项。// 查找第一个匹配项 match := re.FindString("abc 123 def 456") fmt.Println(match) // 输出: 123 // 查找所有匹配项 matches := re.FindAllString("abc 123 def 456", -1) fmt.Println(matches) // 输出: [123 456]
ReplaceAllString
方法来替换匹配的字符串。// 替换匹配项 result := re.ReplaceAllString("abc 123 def 456", "number") fmt.Println(result) // 输出: abc number def number
FindStringSubmatch
方法获取。re = regexp.MustCompile(`(\d+)-(\d+)-(\d+)`) match := re.FindStringSubmatch("2023-06-26") fmt.Println(match) // 输出: [2023-06-26 2023 06 26]
ReplaceAllStringFunc
方法,通过一个自定义函数来替换匹配项。// 定义替换函数 replaceFunc := func(s string) string { return "[" + s + "]" } // 使用替换函数 result := re.ReplaceAllStringFunc("abc 123 def 456", replaceFunc) fmt.Println(result) // 输出: abc [123] def [456]
.
匹配任何单个字符
^
匹配字符串的开头
$
匹配字符串的结尾
*
匹配0或更多前面的字符
+
匹配1或更多前面的字符
?
匹配0或1个前面的字符
[]
字符集,匹配其中的任一字符
|
表示逻辑“或”操作
()
分组,提取子匹配项
通过使用regexp
包,Go语言中的正则表达式提供了强大的文本处理能力,可以满足各种文本匹配和处理需求。