Twitter / X Handle in GO
Match Twitter/X @handles — 1 to 15 characters of letters, digits, or underscores preceded by @.
Try it in the GO tester →Pattern
regexGO
@([A-Za-z0-9_]{1,15})\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`@([A-Za-z0-9_]{1,15})\b`)
input := `Follow @jack and @TwitterDev for updates`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
@ matches the literal at-sign. The capturing group ([A-Za-z0-9_]{1,15}) captures 1–15 characters of the Twitter username alphabet. \b prevents partial matches inside longer words.
Examples
Input
Follow @jack and @TwitterDev for updatesMatches
@jack@TwitterDev
Input
@user_123 liked your postMatches
@user_123
Input
no handles hereNo match
—