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
Example: How to use ReadFull from IO Package in Golang?
How to convert Colorful PNG image to Gray-scale?
How can we reverse a simple string in Go?
Split a string at uppercase letters using regular expression in Golang
How to check string contains uppercase lowercase character in Golang?
How to wait for Goroutines to Finish Execution?
Golang Slice interface and array concatenation
Golang download image from given URL
How to Convert string to integer type in Go?
Create and Print Multi Dimensional Slice in Golang