Regex to Match a Port Number
Copy the pattern, paste numbers, and see which are valid ports. Below: how the alternation enforces the 65535 ceiling.
Regex pattern
/\b(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b/g
This matches a TCP/UDP port number in the valid range 0–65535, rejecting out-of-range values like 70000. It validates the number only, not whether the port is open or privileged.
What this pattern matches
It matches an integer in the valid port range 0–65535 and rejects out-of-range numbers like 65536 or 99999.
Why the alternation
Regex can't compare numeric magnitude, so the range is decomposed into digit-length buckets:
6553[0-5], 655[0-2]\d, 65[0-4]\d{2}, 6[0-4]\d{3} — five-digit numbers up to 65535.
[1-5]\d{4} — 10000–59999.
[1-9]\d{0,3} — 1–9999 without leading zeros.
0 — the port zero itself.
Validation
Anchor with ^…$ to validate a lone field instead of scanning text with word boundaries.
Use it in your code
import re
text = "80 443 8080 65535 65536 99999 0 22"
pattern = r'''\b(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b'''
for m in re.finditer(pattern, text):
print(m.group())
const text = "80 443 8080 65535 65536 99999 0 22";
const re = new RegExp(String.raw`\b(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b`, "g");
console.log(text.match(re));
FAQ
Why not just \d{1,5}?
That would accept 99999, which is not a valid port. The alternation enforces the true 65535 ceiling.
Does it allow port 0?
Yes. Port 0 is technically valid (wildcard). Remove the |0 branch and change [1-9] logic if you want 1-65535 only.
It's easier to check the range in code — why regex?
For validating a single field in a form or config where a numeric parse isn't convenient, a range regex is handy. In code, parsing to int and comparing is clearer.