Remove All Non-Alphanumeric Characters

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, gammar, 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
    "fmt"
    "regexp"
)

func main() {

    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]+")
    if err != nil {
        panic(err)
    }

    processedString := reg.ReplaceAllString(example, "")

    fmt.Printf("From %s to %s\n", example, processedString)
    // = From $G0Ph4r-C0ding.com$* to G0Ph4rC0dingcom
}

golang how to strip non-alphanumerical characters from a string