How to check if a string is in a valid format ("XXX-XXX-XXXX") with numbers in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"regexp"
)

func main() {
	s := "771-290-1652"
	if isValidFormat(s) {
		fmt.Println("Valid")
	} else {
		fmt.Println("Not Valid")
	}

	s = "771-29-162"
	if isValidFormat(s) {
		fmt.Println("Valid")
	} else {
		fmt.Println("Not Valid")
	}

	s = "771-AB1-1620"
	if isValidFormat(s) {
		fmt.Println("Valid")
	} else {
		fmt.Println("Not Valid")
	}
}

func isValidFormat(s string) bool {
	pattern := "(\\d{3}-)?\\d{3}-\\d{4}"
	
	matched, _ := regexp.MatchString(pattern, s)
	
	return matched
}


/*
run:
 
Valid
Not Valid
Not Valid
 
*/

 



answered Nov 16, 2024 by avibootz
...