pattern.go 788 B

123456789101112131415161718192021222324252627282930313233343536
  1. // pattern.go
  2. package main
  3. import (
  4. "fmt"
  5. "regexp"
  6. "strconv"
  7. )
  8. func main() {
  9. searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18" // string to search
  10. pat := "[0-9]+.[0-9]+" // pattern search for in searchIn
  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. str := re.ReplaceAllString(searchIn, "##.#") // replace pat with "##.#"
  20. fmt.Println(str)
  21. // using a function :
  22. str2 := re.ReplaceAllStringFunc(searchIn, f)
  23. fmt.Println(str2)
  24. }
  25. /* Output:
  26. Match found!
  27. John: ##.# William: ##.# Steve: ##.#
  28. John: 5156.68 William: 9134.46 Steve: 11264.36
  29. */