Golang Code

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

· 122 words · 1 minute read #alphanum #clean #compile #parsing #regex #regexp #remove #replace #strings #symbols

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.

package main

import (

func main() {

    example := "#GoLangCode!$!"

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

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

    // Will output: 'A string of #GoLangCode!$! becomes GoLangCode'
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.

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!