Answer the question
In order to leave comments, you need to log in
How to parse a string and change certain characters?
Hello! There is such a question:
How can a string be parsed and replace certain characters. For example:
Given: +999 99 999 99 99 or +999 (99) -999-99-99
Need to be: +999999999999.
I'm a beginner, so I can explain more easily.
Answer the question
In order to leave comments, you need to log in
Without regular expressions:
https://play.golang.org/p/SIqQunrMQHI
import (
"strings"
)
func normalize(s string) string {
var sb strings.Builder
for _, r := range s {
switch {
case '0' <= r && r <= '9':
case r == '+':
default:
continue
}
sb.WriteRune(r)
}
return sb.String()
}
import (
"regexp"
"strings"
)
var re = regexp.MustCompile(`(?i)[\d\+]+`)
func normalize(s string) string {
var sb strings.Builder
subs := re.FindAllStringSubmatch(s, -1)
for _, sub := range subs {
sb.WriteString(sub[0])
}
return sb.String()
}
var re = regexp.MustCompile(`(?m)[^+\d]`)
var str = `+999 (99)-999 9999`
fmt.Println(re.ReplaceAllString(str, ""))
Replace spaces with "blank".
https://golang.org/pkg/strings/#ReplaceAll
strings.ReplaceAll("+999 99 999 99 99", " ", "")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question