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 (

func main() {
	test1 := "25-Golang_Go"
	isMatch := regexp.MustCompile(`^[A-Za-z0-9_-]*$`).MatchString(test1)

	test2 := "25#Golang$Go"
	isMatch = regexp.MustCompile(`^[A-Za-z0-9_-]*$`).MatchString(test2)
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