code.oscarkilo.com/okg/who/username.go

..
username.go
username_test.go
who.go
who_test.go
package who

import "regexp"
import "strings"

// UsernameRegex matches a primary //who username: starts with a
// lowercase letter, then up to 31 more lowercase letters,
// digits, hyphens, or underscores.
const UsernameRegex = `[a-z][-a-z0-9_]{0,31}`

// usernamePattern is the compiled, anchored form of
// UsernameRegex, used by IsValidUsername.
var usernamePattern = regexp.MustCompile(
  `^` + UsernameRegex + `$`)

// IsValidUsername returns true if the username matches
// UsernameRegex.
func IsValidUsername(username string) bool {
  return usernamePattern.MatchString(username)
}

// FullUsernameRegex matches both regular usernames and
// sub-usernames (parent.child).
const FullUsernameRegex = UsernameRegex +
  `(\.` + UsernameRegex + `)?`

// IsSubUsername returns true if username is a valid sub-username
// (contains exactly one dot, both parts valid).
func IsSubUsername(username string) bool {
  dot := strings.IndexByte(username, '.')
  if dot < 0 {
    return false
  }
  return IsValidUsername(username[:dot]) &&
    IsValidUsername(username[dot+1:])
}

// ParentUsername returns the parent portion of a sub-username,
// or "" if not a sub-username.
func ParentUsername(username string) string {
  dot := strings.IndexByte(username, '.')
  if dot < 0 {
    return ""
  }
  return username[:dot]
}