Skip to content

Instantly share code, notes, and snippets.

@djherbis
Last active August 29, 2015 14:19
Show Gist options
  • Save djherbis/26bf47efbe2deb0d2405 to your computer and use it in GitHub Desktop.
Save djherbis/26bf47efbe2deb0d2405 to your computer and use it in GitHub Desktop.
Go "Not" Regex Prefix
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
var valid = regexp.MustCompile(Not("abcd"))
// Matches
fmt.Println(valid.MatchString("xabcd"))
fmt.Println(valid.MatchString("xyz"))
fmt.Println(valid.MatchString("abxyz"))
fmt.Println(valid.MatchString("a"))
fmt.Println(valid.MatchString("ab"))
fmt.Println(valid.MatchString("abc"))
// No Match
fmt.Println(valid.MatchString("abcdxyz"))
fmt.Println(valid.MatchString("abcd"))
fmt.Println(valid.MatchString("abcde"))
}
// Generate a regexp which matches strings without the prefix m
func Not(m string) string {
buf := bytes.NewBufferString("")
sep := ""
opt := ""
for i, a := range m {
fmt.Fprintf(buf, "%v%v([^%v].*)%s", sep, m[:i], string(a), opt)
sep = "|"
opt = "?"
}
return fmt.Sprintf("^(%s)$", buf.String())
}
@djherbis
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment