To remove all non-alphanumeric characters from a string in Golang, you can use the regular expressions package regexp
and replace the non-alphanumeric characters with an empty string. Here's an example code snippet:
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello! This is a string with @#$ non-alphanumeric characters 1234."
// Define the regular expression to match non-alphanumeric characters
regex := regexp.MustCompile("[^a-zA-Z0-9]+")
// Replace all non-alphanumeric characters with an empty string
result := regex.ReplaceAllString(str, "")
fmt.Println("Original String:", str)
fmt.Println("Modified String:", result)
}
Output:
Original String: Hello! This is a string with @#$ non-alphanumeric characters 1234.
Modified String: HelloThisisastringwithnonalphanumericcharacters1234
The regexp.MustCompile
function is used to compile the regular expression pattern [^a-zA-Z0-9]+
, which matches any character that is not a letter or a digit. The ReplaceAllString
function is then used to replace all occurrences of the matched pattern with an empty string.