I want to replace all the numbers in a string with zeros, and ideally consecutive numbers should be replaced with one zero.abc826def47
should become abc0def0
I have tried two methods:
Using regex:
var numbersRegExp = regexp.MustCompile("[0-9]+")
func normalizeNumbers(str string) string{
return numbersRegExp.ReplaceAllString(str, "0")
}
Using strings.Replace
import s "strings"
func normalizeNumbers(str string) string{
str = s.Replace(str, "1", "0", -1)
str = s.Replace(str, "2", "0", -1)
str = s.Replace(str, "3", "0", -1)
str = s.Replace(str, "4", "0", -1)
str = s.Replace(str, "5", "0", -1)
str = s.Replace(str, "6", "0", -1)
str = s.Replace(str, "7", "0", -1)
str = s.Replace(str, "8", "0", -1)
str = s.Replace(str, "9", "0", -1)
str = s.Replace(str, "00", "0", -1)
return str
}
The second method without using regex seems to be a little faster, but still very slow when working with about 100k strings, and it does not replace consecutive numbers well.
Is there a better way of doing this?