Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Created August 18, 2011 16:34
Show Gist options
  • Save kylelemons/1154473 to your computer and use it in GitHub Desktop.
Save kylelemons/1154473 to your computer and use it in GitHub Desktop.
Switch on a regex pattern
package main
import "fmt"
import "regexp"
var email = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+$`)
var shortPhone = regexp.MustCompile(`^[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]$`)
var longPhone = regexp.MustCompile(`^[(]?[0-9][0-9][0-9][). \-]*[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]$`)
func main() {
contacts := []string{
"(111) 555-4444",
"[email protected]",
"555-1234",
"123.555.4567",
"1 infinite loop",
}
for _, contact := range contacts {
switch {
case email.MatchString(contact):
fmt.Println(contact, "is an email")
case shortPhone.MatchString(contact):
fmt.Println(contact, "is a short phone number")
case longPhone.MatchString(contact):
fmt.Println(contact, "is a long phone number")
default:
fmt.Println(contact, "is not recognized")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment