Last active
August 29, 2015 14:19
-
-
Save djherbis/26bf47efbe2deb0d2405 to your computer and use it in GitHub Desktop.
Go "Not" Regex Prefix
This file contains hidden or 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 ( | |
"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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On the playground:
https://play.golang.org/p/piSoC9RB_l