regex multiline mode

Fix the regex pattern in line A, to replace all consecutive 0s to one 0 when 0 is the beginning of the line.The expected output is like:1000101

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. s := `100
  8. 00
  9. 0
  10. 1
  11. 0
  12. 0
  13. 1`
  14. pattern := regexp.MustCompile("0(0|\n)*0") //A
  15. s = pattern.ReplaceAllString(s, "0")
  16. fmt.Println(s)
  17. }

Answer

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. s := `100
  8. 00
  9. 0
  10. 1
  11. 0
  12. 0
  13. 1`
  14. pattern := regexp.MustCompile("(?m:^0(0|\n)*0)")
  15. s = pattern.ReplaceAllString(s, "0")
  16. fmt.Println(s)
  17. }