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

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'

Leave a Reply

Your email address will not be published. Required fields are marked *