go

                   simple, fast, safe, concurrent, fun
  1. Code
  2. Search
  3. Subscribe
  4. Archive
  5. Random

explorations into google's new language by nick quaranto

Newer
Older
  • 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 regexp package. The easiest way is just to use regexp.MatchString:

    matched, error := regexp.MatchString("[0-9]+", "1337")
    This returns a boolean, matched, and an os.Error in 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 ()

    1. vicserte liked this
    2. golang posted this

Field Notes Theme. Designed by Manasto Jones. Powered by Tumblr.