How to remove special characters from a string in GoLang?
Special characters typically include any character that is not a letter or number, such as punctuation and whitespace. Removing special characters from a string results in a string containing only letters and numbers.
Remove Special Characters
We use the ReplaceAllString() method from regex package to replace the matched non-alphanumeric characters with the empty string "".
Example
// Golang program to remove
// special characters from string
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang@%Programs#"
str = regexp.MustCompile(`[^a-zA-Z0-9 ]+`).ReplaceAllString(str, "")
fmt.Println(str)
}
Output
GolangPrograms
Most Helpful This Week
Implementing Multiple Interfaces in Go Programming Language
Assign Default Value for Struct Field
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Program in Golang to print Pyramid of Numbers
Golang program for implementation of Binary Search
How to remove all line breaks from a string in Golang?
Most Helpful This Week
How to blur an image in Golang?How to check pointer or interface is nil?How to read current directory using Readdir?Find out how many logical processors used by current processURL parser in GolangHow to convert Colorful PNG image to Gray-scale?Example of Sscan vs Sscanf vs Sscanln from FMT PackageGolang Convert String into Snake CaseHow to add Watermark or Merge two image?How to print string with double quote in Go?