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 string contains uppercase lowercase character in Golang?
How to trim leading and trailing white spaces of a string in Golang?
How to check if a string contains only letters in Golang?
How to remove all line breaks from a string in Golang?
How to remove special characters from a string in GoLang?
How to check lowercase characters in a string in Golang?
How to check if a string contains a numbers in Golang?
Golang String Concatenation
How to remove multiple spaces in a string in GoLang?
How to check if a string contains certain characters in Golang?