Skip to content

Instantly share code, notes, and snippets.

@jlinoff
Last active February 15, 2017 17:00
Show Gist options
  • Save jlinoff/631fb7b8a57bca86c2c46e8b2eab04d8 to your computer and use it in GitHub Desktop.
Save jlinoff/631fb7b8a57bca86c2c46e8b2eab04d8 to your computer and use it in GitHub Desktop.
Simple program to test go regular expressions.
// Simple program to test go regular expressions.
//
// You specify a regular expression followed by a list of
// strings to test against it. The program reports whether
// each string matched.
//
// Here is how you build it:
//
// $ go build trex.go
//
// Here is how you use it:
//
// $ go build trex.go
// $ ./trex '\bmain\b' 'foomain' 'foo.main' 'foo.main.bar' 'mainx'
// '\bmain\b' NO-MATCH 'foomain'
// '\bmain\b' MATCH 'foo.main'
// '\bmain\b' MATCH 'foo.main.bar'
// '\bmain\b' NO-MATCH 'mainx'
//
package main
import (
"fmt"
"log"
"os"
"regexp"
)
func main() {
// Make sure that we have the minimum.
if len(os.Args) < 3 {
log.Fatalf("ERROR: Not enough arguments.\n\tYou need to specify a regexp and at least one test.\n")
}
// Compile the regular expressions.
re, err := regexp.Compile(os.Args[1])
if err != nil {
log.Fatalf("ERROR: invalid regexp: %v\n", err)
}
// Test the other arguments to see if the match or not.
for i := 2; i < len(os.Args) ; i++ {
arg := os.Args[i]
if re.MatchString(arg) {
fmt.Printf("'%s' MATCH '%s'\n", re, arg)
} else {
fmt.Printf("'%s' NOMATCH '%s'\n", re, arg)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment