Skip to content

Instantly share code, notes, and snippets.

@Tzeentchful
Created June 21, 2017 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tzeentchful/78ade6f92ade5d7cf3c916b43cca809c to your computer and use it in GitHub Desktop.
Save Tzeentchful/78ade6f92ade5d7cf3c916b43cca809c to your computer and use it in GitHub Desktop.
package main
import "regexp"
func main() {
}
func regex(name string) bool {
ok, _ := regexp.MatchString("^[a-zA-Z0-9_]+$", name)
return ok
}
func regexreplace(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 48 || s[i] < 65 && s[i] > 57 || s[i] > 122 {
return false
}
}
return true
}
package main
import (
"math/rand"
"testing"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func BenchmarkRegex(b *testing.B) {
name := randSeq(16)
b.ResetTimer()
for i := 0; i < b.N; i++ {
regex(name)
}
}
func BenchmarkLoop(b *testing.B) {
name := randSeq(16)
b.ResetTimer()
regexreplace(name)
for i := 0; i < b.N; i++ {
regexreplace(name)
}
}
var validnames = [...]string{"Notch", "Geb", "Iron_Man1", "asdfghteahlejhgs", "_TestMe_", "l1lyPad00_"}
var invalidnames = [...]string{"(*$&", "The-King68", " hell0", "symb@l"}
func TestRegex(t *testing.T) {
for i := 0; i < len(validnames); i++ {
result := regex(validnames[i])
if !result {
t.Fail()
}
}
for i := 0; i < len(invalidnames); i++ {
result := regex(invalidnames[i])
if result {
t.Fail()
}
}
}
func TestReplace(t *testing.T) {
for i := 0; i < len(validnames); i++ {
result := regexreplace(validnames[i])
if !result {
t.Fail()
}
}
for i := 0; i < len(invalidnames); i++ {
result := regexreplace(invalidnames[i])
if result {
t.Fail()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment