Regular Expression for URL-Friendly Titles

The following Go code snippet will convert a string from this: Wow! This message's getting some _good_ publicity! To this: wow-this-messages-getting-some-good The function The function itself, and its imports: import ( "math" "regexp" "strings" ) // Converts a string to a lowercase, hyphen-separated string of max length 36 func getTitleURLFromString(title string) (output string) { // first, strip out any special characters re := regexp.MustCompile(`(?m)[^\d^A-Z^a-z^\-^\s]`) substitution := "" output = re....

April 18, 2020 · 2 min · Charles M. Knox

String Compression in Go

Here’s how to compress and decompress a string in Golang using the gzip library. package main import ( "compress/gzip" "fmt" "bytes" "io/ioutil" ) // Credit where credit is due! // https://stackoverflow.com/a/19267224 func compressString(str string) (string, error) { var b bytes.Buffer gz := gzip.NewWriter(&b) if _, err := gz.Write([]byte(str)); err != nil { fmt.Println(fmt.Sprintf("Compress string failure %v", err)) return "", err } if err := gz.Close(); err != nil { fmt.Println(fmt.Sprintf("Compress string closure failure %v", err)) return "", err } return string(b....

April 18, 2020 · 1 min · Charles M. Knox

Go Regular Expression for Emails

It was a bit annoying, but the regular expression on this site almost worked out of the box. I had to add in a few line breaks: package main import ( "fmt" "regexp" ) var emailRegEx = regexp.MustCompile( `^(?:[a-z0-9!#$%&'*+/=?^_`+ "`"+ `{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`+ "`"+ `{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])`) func verifyEmail(email string) bool { if (emailRegEx.MatchString(email) == true) { return true } return false } func main() { fmt.Println(verifyEmail("[email protected]")) } Go Playground link: https://play.golang.org/p/Gq67bAJeK2r

April 17, 2020 · 1 min · Charles M. Knox