-
regexp.MatchString
Everyone loves Regular Expressions, right? Instead of writing an annoying parser for our first assignment, expr, it was definitely easier to just use Go’s built in
regexppackage. The easiest way is just to useregexp.MatchString:
This returns a boolean,matched, error := regexp.MatchString("[0-9]+", "1337")matched, and anos.Errorin the second variable. This whole multiple return thing is pretty crazy. So using it in an if statement is a bit clunky if we want to do it in one line. Here’s a short example:package main import ( "os" "regexp" "fmt" ) func main() { if len(os.Args) == 1 { fmt.Println("Usage: regexp [string]") os.Exit(1) } else if m, _ := regexp.MatchString("^[0-9]+$", os.Args[1]); m { fmt.Println("Totally numbers") } else { fmt.Println("Totally not numbers") } }% ./bin/regexp Usage: regexp [string] % ./bin/regexp 1234 Totally numbers % ./bin/regexp abcd Totally not numbers % ./bin/regexp 12zx34 Totally not numbers
I suppose it could be two lines, but why bother? Check out the package documentation for more, and the code is here on GitHub.Posted on March 15, 2010 with 1 note ()