We often need to remove symbols and special characters from the strings we’re using (especially with currency!). This post shows how you can keep the letters and numbers, but remove any punctuation, symbols, grammar, etc. For example, if a user types in “$1,000” you can turn it into “1000”.
We use the regexp package to do this, first building a regex with .Compile() then running the string through that regex with .ReplaceAllString(). Finally with display and compare both strings.
packagemainimport("fmt""regexp")funcmain(){example:="$G0Ph4r-C0ding.com$*"// Make a regex to say we only want lower + uppercase letters and numbers
reg,err:=regexp.Compile("[^a-zA-Z0-9]+")iferr!=nil{panic(err)}processedString:=reg.ReplaceAllString(example,"")fmt.Printf("From %s to %s\n",example,processedString)// = From $G0Ph4r-C0ding.com$* to G0Ph4rC0dingcom
}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.