TCP/UDP Port Number in GO
Match port numbers (1–65535) following a colon, as you'd find in host:port strings.
Try it in the GO tester →Pattern
regexGO
:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]?\d{1,4})\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]?\d{1,4})\b`)
input := `http://localhost:8080`
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
The alternation enforces the 0–65535 range. Requires a leading colon for context, followed by a word boundary.
Examples
Input
http://localhost:8080Matches
:8080
Input
db.example.com:5432Matches
:5432
Input
api:65535Matches
:65535