To remove special characters from a string in Go, you can use the `regexp` package with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.regexp.MustCompile("[^a-zA-Z0-9 ]")
to match all non-alphanumeric characters and spaces.re.ReplaceAllString(str1, "")
to replace all matches with an empty string and store the result in str1
.str1
.package main
import (
"fmt"
"regexp"
)
func main() {
str1 := "Hello! World!"
re := regexp.MustCompile("[^a-zA-Z0-9 ]")
str1 = re.ReplaceAllString(str1, "")
fmt.Println("Modified string:", str1)
}
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.regexp.MustCompile("[^a-zA-Z0-9 ]")
to match all non-alphanumeric characters and spaces.re.ReplaceAllString(str2, "")
to replace all matches with an empty string and store the result in str2
.str2
.package main
import (
"fmt"
"regexp"
)
func main() {
str2 := "apple@banana"
re := regexp.MustCompile("[^a-zA-Z0-9 ]")
str2 = re.ReplaceAllString(str2, "")
fmt.Println("Modified string:", str2)
}
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in Go language with well detailed examples.