9.2 regexp 包

正则表达式语法和使用的详细信息请参考 维基百科

在下面的程序里,我们将在字符串中对正则表达式进行匹配。

如果是简单模式,使用 Match 方法便可:

  1. ok, _ := regexp.Match(pat, []byte(searchIn))

变量 ok 将返回 true 或者 false,我们也可以使用 MatchString

  1. ok, _ := regexp.MatchString(pat, searchIn)

更多方法中,必须先将正则通过 Compile 方法返回一个 Regexp 对象。然后我们将掌握一些匹配,查找,替换相关的功能。

示例 9.2 pattern.go

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. )
  7. func main() {
  8. //目标字符串
  9. searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
  10. pat := "[0-9]+.[0-9]+" //正则
  11. f := func(s string) string{
  12. v, _ := strconv.ParseFloat(s, 32)
  13. return strconv.FormatFloat(v * 2, 'f', 2, 32)
  14. }
  15. if ok, _ := regexp.Match(pat, []byte(searchIn)); ok {
  16. fmt.Println("Match Found!")
  17. }
  18. re, _ := regexp.Compile(pat)
  19. //将匹配到的部分替换为"##.#"
  20. str := re.ReplaceAllString(searchIn, "##.#")
  21. fmt.Println(str)
  22. //参数为函数时
  23. str2 := re.ReplaceAllStringFunc(searchIn, f)
  24. fmt.Println(str2)
  25. }

输出结果:

  1. Match Found!
  2. John: ##.# William: ##.# Steve: ##.#
  3. John: 5156.68 William: 9134.46 Steve: 11264.36

Compile 函数也可能返回一个错误,我们在使用时忽略对错误的判断是因为我们确信自己正则表达式是有效的。当用户输入或从数据中获取正则表达式的时候,我们有必要去检验它的正确性。另外我们也可以使用 MustCompile 方法,它可以像 Compile 方法一样检验正则的有效性,但是当正则不合法时程序将 panic(详情查看第 13.2 节)。

链接