Remove all Non-Alphanumeric Characters from a String (with help from regexp)

· 137 words · 1 minute read

It’s often useful be be able to remove characters from a string which aren’t relevant, for example when being passed strings which might have $ or £ symbols in, or when parsing content a user has typed in. To do this we use the regexp package where we compile a regex to clear out anything with isn’t a letter of the alphabet or a number.

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

import (
    "fmt"
    "log"
    "regexp"
)

func main() {

    example := "#GoLangCode!$!"

    // Make a Regex to say we only want letters and numbers
    reg, err := regexp.Compile("[^a-zA-Z0-9]+")
    if err != nil {
        log.Fatal(err)
    }
    processedString := reg.ReplaceAllString(example, "")

    fmt.Printf("A string of %s becomes %s \n", example, processedString)
}

remove alpha numeric chars

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!