Created
August 18, 2011 16:34
-
-
Save kylelemons/1154473 to your computer and use it in GitHub Desktop.
Switch on a regex pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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