How to check if a string contains only letters in Golang?
Checking if a string contains letters returns True if the string contains all letters, and False otherwise. Letters include any alphabetic character and excludes digits, punctuation, and other special characters.
Example using unicode.IsLetter function
package main
import (
"fmt"
"unicode"
)
func IsLetter(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) {
return false
}
}
return true
}
func main() {
fmt.Println(IsLetter("Golang")) // true
fmt.Println(IsLetter("Golang#54")) // false
}
Example using strings.Contains function
package main
import (
"fmt"
"strings"
)
const alpha = "abcdefghijklmnopqrstuvwxyz"
func alphaOnly(s string) bool {
for _, char := range s {
if !strings.Contains(alpha, strings.ToLower(string(char))) {
return false
}
}
return true
}
func main() {
fmt.Println(alphaOnly("Golang")) // true
fmt.Println(alphaOnly("Golang#54")) // false
}
Example using Regex
package main
import (
"fmt"
"regexp"
)
var IsLetter = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString
func main() {
fmt.Println(IsLetter("Golang")) // true
fmt.Println(IsLetter("Golang#54")) // false
}
Regular expression is widely used for pattern matching. The regexp package provides support for regular expressions, which allow complex patterns to be found in strings. The regexp.MustCompile() function is used to create the regular expression and the MatchString() function returns a bool that indicates whether a pattern is matched by the string.
Most Helpful This Week
How to replace emoji characters in string using regex in Golang?
How to add and update elements in Map?
How to rotate an image?
How to import and alias package names?
Replace any non-alphanumeric character sequences with a dash using Regex
How to declare empty Map in Go?
Golang Get current Date and Time in EST, UTC and MST?
Generate a Keygen of 256 bits
Regular expression to extract numbers from a string in Golang
Strip all white spaces, tabs, newlines from a string