To keep only alphabets in a string in Go, you can use regular expressions from the 'regexp' package to remove non-alphabetic characters.
In this example,
str1
with a value of "Hello123 World"
.[^a-zA-Z]
to match non-alphabetic characters.ReplaceAllString()
method to replace all non-alphabetic characters with an empty string.str1
.package main
import (
"fmt"
"regexp"
)
func main() {
str1 := "Hello123 World"
reg := regexp.MustCompile("[^a-zA-Z]")
str1 = reg.ReplaceAllString(str1, "")
fmt.Println("Modified string:", str1)
}
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.[^a-zA-Z]
to match non-alphabetic characters.ReplaceAllString()
method to replace all non-alphabetic characters with an empty string.str2
.package main
import (
"fmt"
"regexp"
)
func main() {
str2 := "apple@banana"
reg := regexp.MustCompile("[^a-zA-Z]")
str2 = reg.ReplaceAllString(str2, "")
fmt.Println("Modified string:", str2)
}
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Go language with well detailed examples.