Twitter / X URL in GO
Match Twitter/X profile and status URLs, capturing the handle and (optional) tweet ID.
Try it in the GO tester →Pattern
regexGO
https?:\/\/(?:www\.)?(?:twitter|x)\.com\/([A-Za-z0-9_]{1,15})(?:\/status\/(\d+))? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`https?:\/\/(?:www\.)?(?:twitter|x)\.com\/([A-Za-z0-9_]{1,15})(?:\/status\/(\d+))?`)
input := `https://twitter.com/jack/status/20`
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
https?:\/\/(?:www\.)?(?:twitter|x)\.com matches the domain — both legacy twitter.com and current x.com, with optional www. ([A-Za-z0-9_]{1,15}) captures the handle. (?:\/status\/(\d+))? optionally captures a tweet ID for status URLs.
Examples
Input
https://twitter.com/jack/status/20Matches
https://twitter.com/jack/status/20
Input
Profile: https://x.com/elonmuskMatches
https://x.com/elonmusk
Input
no twitter linksNo match
—