How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
A string that contains only letters, number, underscores, and dashes had no other characters such as operators or special characters. For example, "golang-1" meets these criteria, but "golang@1" does not.
Use Regex to verify a string only contains letters, numbers, underscores and dashes
package main
import (
"fmt"
"regexp"
)
func main() {
test1 := "25-Golang_Go"
isMatch := regexp.MustCompile(`^[A-Za-z0-9_-]*$`).MatchString(test1)
fmt.Println(isMatch)
test2 := "25#Golang$Go"
isMatch = regexp.MustCompile(`^[A-Za-z0-9_-]*$`).MatchString(test2)
fmt.Println(isMatch)
}
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 check if a string contains a numbers in Golang?
Strip all white spaces, tabs, newlines from a string
How to check if a string contains a substring in Golang?
How to remove special characters from a string in GoLang?
How to check if a string contains only letters in Golang?
How to trim leading and trailing white spaces of a string in Golang?